C++ 如何在两个Loki函子之间正确地共享具有状态的函子?
我使用Loki::Functor进行回调,我希望在两个回调之间共享一个Functor(定义了合适的C++ 如何在两个Loki函子之间正确地共享具有状态的函子?,c++,state,functor,loki,C++,State,Functor,Loki,我使用Loki::Functor进行回调,我希望在两个回调之间共享一个Functor(定义了合适的操作符()成员函数的对象)。这个函子需要保持状态,以便两个回调都能看到它 快速测试表明,使用通过值传递的函子构造Loki函子与使用成员函数指针构造函数的结果不同: #include "loki/Functor.h" struct Bar { int x; void inc() { ++x; } int operator()() { return x; } int get() { r
操作符()
成员函数的对象)。这个函子需要保持状态,以便两个回调都能看到它
快速测试表明,使用通过值传递的函子构造Loki函子与使用成员函数指针构造函数的结果不同:
#include "loki/Functor.h"
struct Bar {
int x;
void inc() { ++x; }
int operator()() { return x; }
int get() { return x; }
};
Bar b;
Loki::Functor<int, Loki::NullType> f1(b);
Loki::Functor<int, Loki::NullType> f2(&b, &Bar::get);
Loki::Functor<int, Loki::NullType> f3(&b, &Bar::operator());
cout << f1() << endl; // prints '0'
cout << f2() << endl; // prints '0'
cout << f3() << endl; // prints '0'
b.inc();
cout << f1() << endl; // prints '0'
cout << f2() << endl; // prints '1'
cout << f3() << endl; // prints '1'
#包括“loki/Functor.h”
结构条{
int x;
void inc(){++x;}
int运算符(){return x;}
int get(){return x;}
};
b栏;
Loki::函子f1(b);
Loki::函子f2(&b,&Bar::get);
Loki::函子f3(&b,&Bar::operator());
我真的很惊讶有人还在使用Loki
。上一次发布是大约8年前,最近一次发布是在2009年。我在一个不允许使用全局静态变量的自定义环境中工作(因此排除了Boost::function和bind),使用的是不支持lambdas和其他有用特性的LLVM的固定版本。考虑到Loki在编写时对它所依赖的特性的编译器支持很差,但现在看来很好,它非常适合我。当然,如果您知道其他库可能值得一看,考虑到我的限制,我洗耳恭听。哪个bind/function实现使用全局静态变量?如果你只是指占位符,那么很容易修复。是的,Boost中的占位符-如果很容易修复,我很想知道如何修复,因为我非常喜欢Boost::function。查看Boost/bind/placeholders.hpp
。您将看到3种不同的样式来定义它们。对你来说,使用函数似乎是合适的。gcc采用不同的方法,将占位符定义为extern const
。