Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

We have a legacy system that uses boost::function intensively, now it's decided to move to newer modern C++ standards. Suppose we have a legacy function like this:

void someFunction(boost::function<void(int)>);

Is it safe to directly pass in a C++11 function?

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

Does boost::function also handles standard C++11 lambda gracefully?

// will this also work?
someFunction([](int x)->void{
    //some implementation
});
like image 593
Fei Avatar asked Feb 07 '23 12:02

Fei


1 Answers

Yes this will work.

The important thing is that you shouldn't confuse type safety with compatibility. You're not passing std::function as a boost::function. You're telling the compiler to wrap you std::function into a boost::function.

That might not be efficient - as each will add another layer of indirection on invocation. But it will work.

Same thing goes for lambdas: there's nothing magic about lambdas, it's just syntactic sugar for a function object.

like image 181
sehe Avatar answered May 10 '23 16:05

sehe