C 类变量STD ::功能具有默认功能,并且可以更改

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

本文关键字:功能 默认 STD 类变量      更新时间:2023-10-16

需要在类内具有具有默认功能的函数变量,并且可以覆盖其功能。示例我喜欢/想做(不幸的是失败):

#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;
}

我知道,此代码不会编译。任何人都可以帮助解决这个问题,或者推荐一些东西。如果还有另一种实现此逻辑的方法,则不需要是STD ::功能。也许应该使用lambda?!

更改为:

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

实时演示

解决方案最小更改:

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;}
};