将C++ 11 std :: function传递给带有boost :: function的遗留函数是否安全

Fei*_*Fei 4 c++ lambda boost c++11 std-function

我们有一个遗留系统,它集中使用boost :: function,现在它决定转向更新的现代C++标准.假设我们有这样的遗留函数:

void someFunction(boost::function<void(int)>);
Run Code Online (Sandbox Code Playgroud)

直接传入C++ 11函数是否安全?

//calling site, new C++11 code
std::function<void(int)> func = [](int x){
    //some implementation
}
someFunction(func); //will this always work?
Run Code Online (Sandbox Code Playgroud)

boost :: function是否也能优雅地处理标准C++ 11 lambda?

// will this also work?
someFunction([](int x)->void{
    //some implementation
});
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 8

是的,这将有效.

重要的是你不应该将类型安全兼容性混淆.你不能传递std::function boost::function.你告诉编译器包装std::function 成一个 boost::function.

这可能效率不高 - 因为每个都会在调用时添加另一层间接.但它会奏效.

lambdas也是如此:lambdas没有什么神奇之处,它只是函数对象的语法糖.