Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?!

like image 724
Samps Avatar asked Jun 16 '16 16:06

Samps


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

like image 159
101010 Avatar answered Sep 29 '22 23:09

101010


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;}
};
like image 28
marcinj Avatar answered Sep 30 '22 01:09

marcinj