Pass function as parameter to parent method from derived class - c++

I have the following code, where the execute() method accepts a function as a parameter and executes it. The start() method then calls execute() in order to run method1().
class Test
{
int Test::start(void)
{
execute(&Test::method1);
return 1;
}
void Test::execute(void(Test::*func)(void))
{
(this->*func)();
}
void Test::method1(void)
{
//Do something...
}
}
Now I want to modify this so I achieve the following:
Create a base class called TestRunner and and move the execute() method to it
Have Test inherit from TestRunner, where it can call the execute() method to run its local methods
I am trying the following, but got stuck in how I should specify the method parameter in execute() i.e. what right now I have as TestRunner::*func.
class TestRunner
{
public:
TestRunner()
{
//Do something...
}
protected:
void execute(void(TestRunner::*func)(void))
{
(this->*func)();
}
}
class Test : TestRunner
{
public:
Test() : TestRunner()
{
}
int start()
{
TestRunner::execute(&Test::method1);
return 1;
}
private:
void method1(void)
{
//Do something
}
}
If I compile the code like it is I obviously get these errors:
no matching function for call to 'Test::execute(void (Test::*)())'
and
no known conversion for argument 1 from 'void (Test::)()' to 'void
(TestRunner::)()'
Can anyone guide me in the right direction here or do I need to do something completely different to achieve what I want?

I've used this answer here to come up with a solution: C++ Pointers to Member Functions Inheritance
Create a callback class:
class Callback
{
public:
virtual ~Callback() { }
virtual void doSomething()=0;
};
Extend the callback class to define how a function is executed and use a template:
template<class T>
class BCallback: Callback
{
public:
~BCallback() { }
BCallback(T *obj, void(T::*fn)()): obj_(obj), fn_(fn) { };
void doSomething()
{
(obj_->*fn_)();
}
private:
T *obj_;
void(T::*fn_)();
};
Use a callback object in the base class:
class TestRunner
{
protected:
void execute(Callback *cb)
{
cb->doSomething();
}
};
Run the method from the derived class:
class Test: TestRunner
{
public:
int start()
{
BCallback<Test> cb(this, &Test::method1);
this->execute(&cb);
return 1;
}
private:
void method1(void)
{
//Do something
}
};

You can use a typedef like this:
typedef void(Test::*Callback)(void);
You can then make your executing function take objects of type Callback. It will look like this Test::execute(Callback).
When calling it, use static_cast<>:
Test tester;
tester.execute(static_cast<Callback>(&DerivedTest::someMethod));
Example Test::execute(Callback) implementation:
Test::execute(Callback cb) {
(this->*cb)();
}
This way you can avoid writing whole two new classes (one of them a template, even!) just to do a simple thing. As a bonus, you can use function overloading to get Test::execute for different function signatures.

Related

Provide PV function content when constructing object in C++

In Java you can create an object whilst at the same time providing (or overloading) abstract functions within the object, thus:
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Whatever in here
}
};
I really like that way of doing it, and was wondering if there was some similar construct in C++.
Basically I want a base class with a couple of PV functions declared in it (amongst other stuff), and the user to create an instance of that class whilst at the same time providing the body of the PV functions.
I know I could create child classes, but that seems a little clunky for what I need, where each child class would be unique and only be used to make one instance each.
I have thought about providing lamdas to the constructor and using those instead of actual member functions, but that really seems messy and hard for a novice user to get their head around - not to mention that it would be too rigid (I'd also like to be able to override some non-pure virtual functions optionally).
So is child classes the only way to go, or is there some lesser-known construct in some newer C++ standard that I don't know about that could do what I want?
To expand a little - the idea is to have a class like:
class Thread {
// other stuff
public:
virtual void setup() = 0;
virtual void loop() = 0;
// other functions, some virtual but not pure
};
Thread threadOne {
void setup() {
// Init code for this thread
}
void loop() {
// Run code for this thread
}
};
Thread threadTwo {
void setup() {
// Init code for this thread
}
void loop() {
// Run code for this thread
}
};
Obviously not that syntax, but it gives you an idea of how I'd like to use the class.
It's intended to be run on an embedded system with a slimmed-down C++ implementation (it's g++ but without the full STL). End users aren't the brightest bunch, so it has to be kept as simple to understand as possible.
Anonymous child classes are the closest to what I'd like (though still not perfect). I can use CPP macros to help abstract some of the class implementation syntactic sugar which would help.
Here's a compilable construct I have come up with. Is there anything "wrong" with this approach given the constraints above?
#define THREAD(NAME, CONTENT) class : public Thread {\
public:\
CONTENT\
} NAME;
class Thread {
private:
uint32_t stack[256]; // 1kB stack
volatile bool _running;
public:
virtual void setup() = 0;
virtual void loop() = 0;
void start();
void stop();
uint8_t state();
static void spawn(Thread *thr);
void threadRunner();
};
void Thread::spawn(Thread *thread) {
thread->threadRunner();
}
void Thread::start() {
Thread::spawn(this);
}
void Thread::threadRunner() {
_running = true;
setup();
while (_running) {
loop();
}
}
void Thread::stop() {
_running = false;
}
uint8_t Thread::state() {
return 0;
}
THREAD(myThread,
void setup() override {
}
void loop() override {
}
)
void setup() {
myThread.start();
}
void loop() {
}
Obviously it doesn't actually do anything yet - the whole of the threading back-end is a separate issue, and will be ported over from some existing code I wrote a few years back. I am mainly interested in simplifying the interface for the end user.
There is multiple possibilities, but I'd stick with something simple and versatile: callbacks and lambdas instead of virtual function and inheritance.
class ActionListener
{
std::function<void(int)> _action_performed;
public:
template<class CB>
ActionListener(CB cb) : _action_performed(cb) {}
void click() { _action_performed(0); }
};
int main()
{
ActionListener al([](int n) { std::cout << "Action Performed #" << n << "\n"; });
al.click(); // prints "Action Performed #0"
}
live demo
I'd also like to be able to override some non-pure virtual functions optionally
Which, semantically speaking, means providing a default behavior. This is possible:
ActionListener(CB cb) : _action_performed(cb) {} // construct an AL with the given callback
ActionListener() : _action_performed(default_action_performed) {} // construct an AL with a default callback
void default_action_performed(int n) { /*...*/ }
well, as you already mentioned, one way would be child classes.
another way would be providing some std::functions (or lambdas), either in the constructor or have some set functions.
store the function as a member and call this once your "virtual" member function is called: If you want it optional:
class MyBase
{
public:
MyBase();
void SetFunc(const std::function<int()>& myFun)
{
m_myFun = myFun;
}
int MyVirtFunc()
{
if(m_myFun)
{
return m_myFun();
}
else
{
return 42;
}
}
private:
std::function<int()> m_myFun;
}
if you want the functions given mandatory, put them in the constructor:
class MyBase
{
public:
MyBase(const std::function<int()>& myFun)
: m_myFun(myFun) {}
int MyVirtFun() { return m_myFun(); }
private:
const std::function<int()> m_myFun;
}

How to automatically call a method or generate code if a subclass derived from a base class?

I have some classes that describe abilities / behaviours, such as flying, or driving etc. Each of these classes has a specific method that must be called to load some data - For example, Flyable has loadFlyData(), Drivable has loadDriveData(). For each class the method name is unique.
I have many derived classes that may inherit from one or more of these behaviour classes. Each of these derived classes has a method called loadData(), in which we should call all the parent behaviour classes methods such as loadFlyData(), loadDriveData() etc.... Is there a way to automatically generate this method using metaprogramming ? Since there are many derived classes, it may be more maintainable if I can generate these methods using metaprogramming...
Behaviour classes : (An object class may have any of these behaviours, and will have to call that classes "load" method...
class Flyable {
void loadFlyData() {
}
};
class Drivable{
void loadDriveData() {
}
};
All object classes derive from Object:
class Object {
virtual void loadData() {
}
};
A derived class:
class FlyingCar : public Object, public Flyable, public Drivable {
virtual void loadData() override {
// How to automatically generate code so that the next two lines are called:
loadFlyData();
loadDriveData();
}
};
Sure is possible. You'll need however to employ some conventions so the code can be generic. See it live.
#include <iostream>
using namespace std;
struct Flyable{
int loadConcreteData(){
cout << "Flyable\n"; return 0;
}
};
struct Drivable{
int loadConcreteData(){
cout << "Drivable\n"; return 0;
}
};
class Object{
virtual void loadData(){
}
};
template<class ...CS>
struct ConcreteLoader : Object, CS... {
void loadData() override {
int load[] = {
this->CS::loadConcreteData()...
};
}
};
class FlyingCar : public ConcreteLoader<Flyable,Drivable>{
};
int main() {
FlyingCar fc;
fc.loadData();
return 0;
}
Changes that need mentioning:
The return type of each concrete Load function had to be changed. This is to facilitate the "array trick" in expanding the parameter pack.
The names of all the load functions are the same, again for the same reason.
Reason (1) may become obsolete once c++17 and fold expressions roll out.
You can make a free function loadXData() that will become a noop if your class isn't X:
namespace detail
{
void loadFlyData(Flyable* ptr) { ptr->loadFlyData(); }
void loadFlyData(...) {}
void loadDriveData(Drivable* ptr) { ptr->loadDriveData(); }
void loadDriveData(...) {}
}
class FlyingCar : public Object, public Flyable, public Drivable{
public:
virtual void loadData()override{
//How to automatically generate code so that the next two lines are called:
detail::loadFlyData(this);
detail::loadDriveData(this);
}
};
demo
Though I think using a common name loadData and just calling it for all variadic parents might be preferable:
template<typename... Policies>
struct ComposedType : Object, Policies...
{
virtual void loadData() override {
int arr[] = {
((void)Policies::loadData(), 0)...
};
(void)arr;
}
};
using FlyingCar = ComposedType<Drivable, Flyable>;
demo
The above loadData could be simplified in C++1z:
virtual void loadData() override {
((void)Policies::loadData(), ...);
}
demo

c++ Why i need pointer casting each time i request method from container object

i have annoying problem where i need to pointer cast pointer member
here is example
class GlobalInterface
{
public:
virtual void DoAction() = 0;
}
class ActionClass_A: public GlobalInterface
{
public:
ActionClass_A(){};
~ActionClass_A(){};
void DoAction() { ..... } ;
void DoSomeActionOnlyForA() { ..... } ;
}
class ActionClass_B: public GlobalInterface
{
public:
ActionClass_B(){};
~ActionClass_B(){};
void DoAction() { ..... } ;
void DoSomeActionOnlyForB() { ..... } ;
}
#include "GlobalInterface.h"
#include "ActionClass_A.h"
#include "ActionClass_B.h"
class GlobalContainer()
{
public:
GlobalContainer(GlobalInterface* _action)
{
pAction = _action;
}
GlobalInterface* getAction() { return pAction; };
private:
GlobalInterface* pAction;
}
// Main
GlobalContainer* pGlobalContainer = new GlobalContainer(new ActionClass_B());
// WHY i need this casting to get the ActionClass_B DoAction()???
((ActionClass_B*)pGlobalContainer->getAction())->DoSomeActionOnlyForA();
i just want to avoid this casting , and call it like this :
and it will know which implamention it should invoke based on the object type
pGlobalContainer->getAction()->DoSomeActionOnlyForA()
or
pGlobalContainer->getAction()->DoSomeActionOnlyForB()
The virtual function in the base class is private. It should work with a public function.
... and it will know which implamention it should invoke based on the
object type.
But you're not letting it decide what implementation it should invoke based on type, you're trying to make that decision yourself by calling DoSomeActionOnlyForA() or DoSomeActionOnlyForB() directly.
This doesn't work because at the moment of the call the static type of the object is GlobalInterface* and the GlobalInterface class doesn't have member functions named like that.
The way to achieve what you want, let each derived class have it's own behavior, is to understand and use virtual functions correctly. For example you could do this:
class GlobalInterface
{
public:
virtual ~GlobalInterface() {}
virtual void DoAction() = 0;
};
class ActionClass_A: public GlobalInterface
{
public:
ActionClass_A() {}
~ActionClass_A() {}
void DoAction()
{
DoSomeActionOnlyForA(); // call specific action for A
}
void DoSomeActionOnlyForA() { /* implement specific action for A */ } ;
};
class ActionClass_B: public GlobalInterface
{
public:
ActionClass_B() {}
~ActionClass_B() {}
void DoAction()
{
DoSomeActionOnlyForB(); // call specific action for B
}
void DoSomeActionOnlyForB() { /* implement specific action for B */ } ;
};
As you can see, you have a virtual function DoAction() that is overridden in each of the derived classes to call the appropriate functionality for that class.
Then you can use it like this:
GlobalContainer* pGlobalContainer = new GlobalContainer(new ActionClass_B());
pGlobalContainer->getAction()->DoAction();
This will call ActionClass_B::DoAction() which in turn calls ActionClass_B::DoSomeActionOnlyForB().
If you instead create the container like this:
GlobalContainer* pGlobalContainer = new GlobalContainer(new ActionClass_A());
then the same call pGlobalContainer->getAction()->DoAction(); will instead call ActionClass_A::DoAction() which in turn calls the appropriate functionality for A.
As you can see, in this case it does indeed call the appropriate function based on the dynamic type of the object (DoAction() from A or from B).

How to test method in google test, using std::function?

I would like to test method "methodToTest" in class A:
typedef std::function F_global;
struct A
{
F_global m_F_global;
A(F_global m_F_global) : p_F_global(m_F_global) {}
void methodToTest()
{
m_F_global(5);
}
};
I have got a mock class:
class RunMock
{
public:
MOCK_METHOD1(run, void (int));
};
Below I have got a test case:
class TestClass : public testing::Test
{
protected:
void SetUp();
std::unique_ptr<A> m_aa;
std::unique_ptr<RunMock> m_runMock;
};
void UecSimplePortTestSuite::SetUp()
{
m_aa = make_unique<A>(m_runMock->run);//IT DOESN'T WORK I DON'T KNOW HOW TO FORWARD A METHOD run from RunMock to constructor
}
TEST_F(UecSimplePortTestSuite, testForwardMessage)
{
EXPECT_CALL(*m_runMock, run(_));
m_aa->methodToTest();
}
Generally I don't know how transfer a method "run" from Mock class "RunMock" in "UecSimplePortTestSuite::SetUp()". I would like to do this, because
I would like to "EXPECT_CALL(*m_runMock, run(_));" in UecSimplePortTestSuite.testForwardMessage to test "methodToTest()".
I think that good idea could be to use lmbda, std::boost::bind or something like this.
You can pass a lambda to the constructor of A in the SetUp() :
m_runMock.reset( new RunMock );
m_aa.reset( new A( [&](int value){ m_runMock->run(value); } );
This :
m_runMock->run
is not going to do what you thing, and it is a compilation error. You can read this parashift QA and here how to use pointer to member function.

how to pass method of child as parameter to function in parent

In the following exceedingly abbreviated classes I would like to define in the base a method (ProcessLines) that would iterate over a set of database records, passing each record as a parameter to a function that is only defined in the child class. Obviously the Base is a virtual class that will never be instantiated on its own.
Class Base {
public:
typedef ProcLineFunc( Long *Line );
void ProcessLines( ProcLineFunc pf);
}
Class Child{
void DoWork( Long *Line) { //do something}
}
I'm not sure how to implement this. If I redeclare ProcessLines in the child and just call the parent method, I get the same error message as if I call ProcessLines in the code that creates the child.
Child c(//something);
c.ProcessLines(c.DoWork);
Gives me a compiler message:
[BCC32 Error] main.cpp(67): E2034 Cannot convert 'bool (* (_closure )(long *))(long )' >to 'int ()(long *)'
Full parser context
main.cpp(56): class Add2Chan
main.cpp(78): decision to instantiate: bool Add2Chan::ProcessByLines()
--- Resetting parser context for instantiation...
main.cpp(67): parsing: bool Add2Chan::ProcessByLines()
I'm fairly new to c++ and the E2034 error message scares the daylights out of me.
Please help. I used a typedef so that I can, in my child classes call ProcessLines multiple times, passing in different functions as I go.
Normally you would do this sort of thing with a protected, pure virtual function:
class Base {
public:
ProcessLines() {
//Logic to process lines here, obviously psuedo-code
while(moreLines) {
ProcessLine(line);
}
}
protected:
virtual void ProcessLine(const Line& line) = 0;
}
class Child : public Base {
protected:
void ProcessLine(const Line& line) { //Logic to process the line for this type }
};
class DifferentChild : public Base {
protected:
void ProcessLine(const Line& line) { //Logic to process the line for DifferentChild }
};
I think this is the kind of thing you're looking for. It appears to me like you're trying to implement polymorphism in an odd way, but this is the normal way to do it in C++.
Instead of using pointers to functions, use pointers to objects. Accept the limitation that your function is going to be called DoWork and nothing else, and there can only be one such function in each class. This is not a bad limitation. Declare the (pure virtual) function in a class (which is called an interface), and derive classes from it (they are said to implement an interface).
struct DoingWork
{
virtual void DoWork(long *Line) = 0; // does some work on a list
};
struct DoingGreatWork: DoingWork
{
virtual void DoWork(long *Line) {printf("Great work\n");}
};
struct DoingSlightWork: DoingWork
{
virtual void DoWork(long *Line) {printf("Slight work\n");}
};
Using this example:
class Base {
public:
void ProcessLines(DoingWork& object) {
//Logic to process lines here
while(moreLines) {
object.DoWork(line);
}
}
};
class Whatever // no need to derive from Base
{
void DoStuff()
{
Base object;
object.ProcessLines(DoingGreatWork());
object.ProcessLines(DoingSlightWork());
}
}
If the working objects have to have access to the calling object, initialize them like this:
class Whatever // no need to derive from Base
{
struct DoingElaborateWork: DoingWork
{
Whatever& caller;
DoingElaborateWork(Whatever& caller): caller(caller) {}
virtual void DoWork(long *Line)
{
printf("Doing work requested by %s\n", caller.name());
}
};
void DoStuff()
{
Base object;
object.ProcessLines(DoingElaborateWork(*this));
}
const char* name() {return "Whatever";}
}
P.S. They say that "in C++03 functions are second-class citizens" because you cannot do with functions what you can do with objects (like this solution i provide). I heard that in C++11 functions are much improved, but i am not sure about the details.
Since you are doing this in C++Builder, you can utilize its __closure extension to do exactly what you asked for (some portions of the VCL do exactly this for their own callbacks):
class Base
{
public:
virtual ~Base() {}
typedef void (__closure *ProcLineFunc)( Long *Line );
void ProcessLines( ProcLineFunc pf);
};
class Child : public Base
{
public:
void DoWork( Long *Line) { //do something}
};
Child c(...);
c.ProcessLines(c.DoWork);