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

Is it safe to pass C++11 std::function to a legacy function that takes boost::function

本文关键字:function 函数 是否 boost 安全 std C++11      更新时间:2023-10-16

我们有一个大量使用 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 没有什么神奇之处,它只是函数对象的语法糖。