jeudi 24 janvier 2019

How to recognize or avoid empt boost::function as std::function

I'm currently working on a code using mostly boost but moving more and more to C++11 and it's std library.

There I had crash while passing an empty boost::function as a callback to a std::function:

#include <boost/function.hpp>
#include <functional>
#include <iostream>

int main()
{
   boost::function <void(void)> boost_f;
   std::function <void(void)> std_f;
   std::cout << "used " << (!std_f) << " " << (!boost_f.empty()) << "\n";

   boost_f = boost::function<void(void)>();
   std_f = boost_f;
   std::cout << "used " << (!std_f) << " " << (!boost_f.empty()) << "\n";

   if( std_f )
      std_f();
}

The std::function claims it has a valid target, but the empty boost::function throws an exception:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_function_call> >'
  what():  call to empty boost::function

Tested with gcc-6.3.1 and clang-4.0.

How could I avoid this problem? Could this be fixed so that an empty boost::function assigned to a std::function gives an empty std::function? Or could I check the std::function explicitly for an empty boost::function assigned to it?

Only avoiding the exception is not the intended solution because the function should behave differently dependent on the callback set or not (and it is often not set, so catching the exception should be avoided too).

Aucun commentaire:

Enregistrer un commentaire