传递一个可能更改为类实例的可调用函数
Passing a callable that may change to an instance of a class
我有一组可调用对象,我想将其关联到特定类节点的实例。Node的每个实例只需要持有一个可调用的,并且可以从成员函数中调用它。假设A、B和C是可调用的,它们可能具有不同的函数签名:
Node n1,n2,n3;
n1.associate(A);
n2.associate(B, 42);
n3.associate(C, "foo");
//...
n1.mem_fn(); //will call A at some point inside some_other_fn()
n2.mem_fn(); //will call B, passing 42 as argument
//...
n1.associate(C, "bar");
n1.mem_fn(); //now C will replace A, and be called from n1::mem_fn() with arg "bar"
我怎样才能做到这一点?可调用项的返回类型可能不同。
不再需要使用std::bind
。Lambdas非常容易用于动态生成可调用对象,该对象还可以根据您的喜好存储任何类型的数据。
class Node
{
private:
std::function<void(void)> fn;
public:
template <typename F, typename ... PARMS>
void associate( F f, PARMS ... parms )
{
// Generate a lambda which captures all given parms
// and if executed, the lambda calls f with all
// the captured parms. This on the fly generated
// lambda will be stored in std::function
fn = [f, parms...](){ f( parms...); };
}
void mem_fn()
{
// Here we simply call our lambda which will call
// the stored function with the also stored parms
fn();
}
};
void A() { std::cout << "A" << std::endl; }
void B( int i ) { std::cout << "B " << i << std::endl; }
void C( const std::string& s ) { std::cout << "C " << s << std::endl; }
// I use exact copy of your code as copy here:
int main()
{
Node n1,n2,n3;
n1.associate(A);
n2.associate(B, 42);
n3.associate(C, "foo");
n1.mem_fn(); //will call A at some point inside some_other_fn()
n2.mem_fn(); //will call B, passing 42 as argument
//...
n1.associate(C, "bar"); //now C will replace A, and be called from n1::mem_fn() with arg "bar"
n1.mem_fn();
}
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 对象实例化调用构造函数的次数太多
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 如何使用非默认构造函数实例化模板化类
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 将可变参数函数的参数封装在类实例中
- 模板化类构造函数的模板实例化
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- std::vector 没有重载函数的实例与参数列表匹配
- C++中的单例实现在调用 getInstance 函数时不会产生相同的类实例
- C++初始化类实例时隐式调用类成员的构造函数
- 受约束的成员函数和显式模板实例化
- 对显式实例化的模板函数的未定义引用
- 将类实例函数绑定到 v8::FunctionTemplate
- lambda作为实例函数指针
- 我的类的静态实例函数不像我预期的那样工作
- 如何在C++中传递指向类实例函数的指针?
- 为什么我可以静态地调用实例函数