c++ - 获取转换为 std::function 的函数对象中的状态

标签 c++ c++11 function-object std-function

我想从函数对象中检索状态。但函数对象已被转换为 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/

相关文章:

c++ - 仿函数 : templated struct vs templated operator()

c++ - 删除 *p 是删除 [] p 的替代方法吗?

c++ - 我的错误,还是英特尔编译器中的错误? sizeof 非静态成员错误

c++ - 派生类对象 - Braced init

c++ - 纳秒分辨率到纳秒纪元的日历时间

C++ 函数对象无法使用 std::for_each 创建 sum (VS2012)

c++ - C++ 中的 funcall : declaring functions that take functions as parameters

c++ - 我可以将 FlatBuffers 序列化/反序列化为 JSON 吗?

c++ - SDL2 : Is it bad to move everything instead of using the view-port?

c++ 比较各种长度 vector 并隔离 "unique"的算法,有点