我们有一个大量使用 boost::function 的遗留系统,现在决定转向更新的现代C++标准。假设我们有一个这样的遗留函数:
void someFunction(boost::function<void(int)>);
直接传入 C++11 函数是否安全?
//calling site, new C++11 code
std::function<void(int)> func = [](int x){
//some implementation
}
someFunction(func); //will this always work?
boost::函数是否也能优雅地处理标准 C++11 lambda?
// will this also work?
someFunction([](int x)->void{
//some implementation
});
是的,这将起作用。
重要的是,您不应该将类型安全与兼容性混淆。你不是把std::function
当作boost::function
传递。您告诉编译器将std::function
包装到boost::function
中。
这可能效率不高 - 因为每个都会在调用时添加另一层间接寻址。但它会起作用。
lambdas 也是如此:lambda 没有什么神奇之处,它只是函数对象的语法糖。