C ++ class variable std :: function, which has default functionality and can be changed

You need to have a function variable inside the class that has default functionality, and its functionality can be overwritten. An example of how I loved / wanted (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 does not compile. Can anyone help fix this or recommend something. There is no need to be std :: function if there is another way to implement this logic. Maybe you need to use lambda ?!

+5
source share
2 answers

Change to:

 class Base { public: std::function<bool()> myFunc = [](){ cout << "by default message this out and return true" << endl; return true; }; }; 

Live demo

+5
source

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;} }; 
+1
source

All Articles