我想从函数对象中检索状态。但函数对象已被转换为 function<>
模板。我该怎么做?
我的意思是:
函数对象:
class Counter {
private:
int counter_;
public:
Counter():counter_(0) {cout << "Constructor() called" << endl;}
Counter(int a):counter_(a) {cout << "Constructor(a) called" << endl;}
void operator()(int sum) {
cout << counter_++ + sum << endl;
}
int getCounter() { return counter_;}
};
主要是.我的第一步是直接使用对象:
int main() {
Counter a(10);
a(0);
a(0);
cout << "Counter: " << a.getCounter() << endl;
其显示:
Constructor(a) called
10
11
Counter: 12
没关系,这就是我所期望的。
但是在
Counter b(10);
function<void(int)> f = b;
f(0);
f(0);
cout << "Counter: " << b.getCounter() << endl;
显示
Constructor(a) called
10
11
Counter: 10
啊!,我以为 f 是真实对象的包装器,所以修改 f
我们真的修改b
。编号:f
有一份 b
的拷贝,但我无法调用 f.getCounter()
那么我如何从 f
获取 State (counter_ var) ?
我不能直接使用Counter
类(在本例中)因为我有一些其他类似的类具有相同的签名“void(int)”并且我想在调用者函数中模糊地使用它们。
我可以避免std::function
模板根本对我的所有函数对象使用公共(public)基类,但我认为有一个解决方案更多 C++11 与 STL 和模板...
那么,有这个解决方案吗?
谢谢
最佳答案
从引用包装器创建函数:
function<void(int)> f = std::ref(b);
给出结果:
Constructor(a) called
10
11
Counter: 12
当然,您需要确保在计数器被销毁后不会调用该函数。
如果您需要从函数对象访问计数器,请使用其target
成员:
if (Counter * c = f.target<Counter>()) {
std::cout << "Counter: " << c->getCounter() << '\n';
} else {
std::cout << "Not a counter.\n";
}
关于c++ - 获取转换为 std::function 的函数对象中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11156651/