C 类变量STD ::功能具有默认功能,并且可以更改
C++ class variable std::function which has default functionality and can be changeable
需要在类内具有具有默认功能的函数变量,并且可以覆盖其功能。示例我喜欢/想做(不幸的是失败):
#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;}
};
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 如何使用默认参数等选择模板专业化
- 如何在C++中调用默认模板功能参数?
- SFINAE - 如果更复杂的功能失败,则回退到默认功能
- 如何比较C 中的两个字符串并使用默认功能
- std ::功能作为默认参数的功能
- 未评估上下文中的默认模板参数和 lambda:错误还是功能?
- 将功能添加到默认复制构造函数中
- 模板的C 功能将第一个参数设置为第二个参数为默认参数
- 默认情况下,如何制作功能指针参数NO-OP
- 将重载函数分配给功能指针作为默认值
- 为模棱两可的超载功能调用创建默认值
- C 类变量STD ::功能具有默认功能,并且可以更改
- 模板函数、功能参数的默认值
- "PlaySound()"播放默认窗口错误声音的功能
- 显式默认和删除的构造函数:VS2012 中是否有任何类似的功能可用
- 提升::变体的默认访客功能
- 是常量变量,默认为内部链接语言特定或编译器特定的功能