Need to have a function variable inside the class which have default functionality and it's functionality can be overwritten. Example how I liked/wanted to do(unfortunately unsuccessfully):
#include <iostream>
#include <functional>
using namespace std;
class Base
{
public:
std::function<bool(void)> myFunc(){
cout << "by default message this out and return true" << endl;
return true;}
};
bool myAnotherFunc()
{
cout << "Another functionality and returning false" << endl;
return false;
}
int main()
{
Base b1;
b1.myFunc(); // Calls myFunc() with default functionality
Base b2;
b2.myFunc = myAnotherFunc;
b2.myFunc(); // Calls myFunc() with myAnotherFunc functionality
return 0;
}
I know, this code doesn't compile. Can anyone help to fix this, or recommend something. Don't need to be std::function, if there is another way to implement this logic. Maybe should use lambda?!
Change to:
class Base {
public:
std::function<bool()> myFunc = [](){
cout << "by default message this out and return true" << endl;
return true;
};
};
Live Demo
Solution with minimal changes:
http://coliru.stacked-crooked.com/a/dbf33b4d7077e52b
class Base
{
public:
Base() : myFunc(std::bind(&Base::defAnotherFunc, this)){}
std::function<bool(void)> myFunc;
bool defAnotherFunc(){
cout << "by default message this out and return true" << endl;
return true;}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With