C ++ 11样式回调? [英] C++11 styled callbacks?
问题描述
我在类中有一个void函数。在旧的C ++中,我会创建一个静态函数,将类名作为参数,并拥有一个我自己的类,它采用了一个静态void函数+ void *让我轻松调用它。
但是,感觉老学校。它也不是模板的感觉,我可以做更多。什么是更现代的方式来创建回调myclassVar.voidReturnVoidParamFunc
使用 std :: function
和lambdas(或 std :: bind()
)存储callable:
#include< functional>
#include< iostream>
class Test
{
public:
void blah(){std :: cout< BLAH! << std :: endl; }
};
class Bim
{
public:
void operator()(){std :: cout< BIM! << std :: endl; }
};
void boum(){std :: cout<< BOUM! << std :: endl; }
int main()
{
//存储对象的成员函数:
Test test;
std :: function< void()> callback = std :: bind(& Test :: blah,test);
callback();
//存储一个可调用的对象(通过拷贝)
callback = Bim {};
callback();
//存储静态函数的地址
callback =& boum;
callback();
//存储一个lambda的副本(这是一个可调用对象)
callback = [&] {test.blah(); }; //通常更清晰,而不是更昂贵 - 比std :: bind()
callback();
}
结果:
< >
BLAH!
BIM!
BOUM!
$ b
BLAH!
编译并运行:http://ideone.com/T6wVp
std :: function
可以用作任何可复制对象,所以随意存储它作为一个回调,像在对象的成员。这也意味着你可以自由地把它放在标准的容器,如 std :: vector< std :: function< void()> < a href =http://www.boost.org/doc/libs/1_51_0/> doc / html / function.html> boost :: function和boost :: bind 已有多年。
I have a void function inside of a class. In old C++ i'd make a function static taking the class name as a parameter and had my own class which took a static void function + a void* for me to easily call it.
However that feels old school. It also isn't templated which feels like i could be doing more. What is a more modern way of creating callbacks to myclassVar.voidReturnVoidParamFunc
Use std::function
and lambdas (or std::bind()
) to store callables:
#include <functional>
#include <iostream>
class Test
{
public:
void blah() { std::cout << "BLAH!" << std::endl; }
};
class Bim
{
public:
void operator()(){ std::cout << "BIM!" << std::endl; }
};
void boum() { std::cout << "BOUM!" << std::endl; }
int main()
{
// store the member function of an object:
Test test;
std::function< void() > callback = std::bind( &Test::blah, test );
callback();
// store a callable object (by copy)
callback = Bim{};
callback();
// store the address of a static function
callback = &boum;
callback();
// store a copy of a lambda (that is a callable object)
callback = [&]{ test.blah(); }; // often clearer -and not more expensive- than std::bind()
callback();
}
Result:
BLAH!
BIM!
BOUM!
BLAH!
Compiles and run: http://ideone.com/T6wVp
std::function
can be used as any copyiable object, so feel free to store it somewhere as a callback, like in object's member. It also means that you can freely put it in standard containers, like std::vector< std::function< void () > >
.
Also note that equivalent boost::function and boost::bind have been available for years.
这篇关于C ++ 11样式回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!