3

I attempted to use boost::function<x> wrapper to store and convert my functional objects and I want to know if there a compile-check for "does a conversion from arbitrary type T to type boost::function<x> exists".

Here is a code example:

struct Functor {
   int operator()(int) {
      return 5;
   }
};

// Should not fire static assertion.
STATIC_ASSERT( (IS_CONVERTIBLE<Functor, 
                               boost::function<int (int)> >::value) );

// Should fire static assertion.
STATIC_ASSERT( (IS_CONVERTIBLE<Functor,
                               boost::function<int (std::string)> >::value) );

Now - does a way to implement the IS_CONVERTIBLE check exist?


I tried to utilize boost::is_convertible type trait check, but it yields true for any Functor type:

bool value1 = boost::is_convertible<Functor, 
                                    boost::function<int (int)> >::value;

bool value2 = boost::is_convertible<Functor,
                                    boost::function<int (std::string)> >::value;

// At this point both 'value1' and 'value2' equal TRUE.

I also had the following attempts:

// Here the results are also always TRUE.
bool value = boost::is_convertible<Functor, 
                                   boost::function1<int, int> >::value;

// This doesn't work, because unary functions are constructed via
// inheritance (the result is always FALSE).
bool value = boost::is_convertible<Functor, 
                                   std::unary_function<int, int>::value;

I really want to be able to check the possibility of such a conversion in compile-time, so if anybody knows how to implement this, I would appreciate that.

Thank you.

Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148

2 Answers2

1

boost::is_convertible yields true when you test whether any type is convertible to any boost::function type because boost::function has a converting constructor template that takes any type.

Because this converting constructor exists, I don't know that there's an easy way you could test whether a type is actually convertible to a std::function.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
1

In addition to what @James wrote, it seems you rather want to have something like is_callable. These class templates handle functions/function pointers and function object classes or references to them for up to 5 parameters. Use them at your own risk :)

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212