Sunday, December 23, 2012

is_callable_with: can a functor be called with a specific signature

I recently was facing the problem to write a function that has to be able to accept function objects with different calling signatures. Depending on the signature different code should be called. So I needed a meta-template function to test this. Let’s call it

    bool is_callable_with<Class,Signature>()      

Given a test class

    struct A { void operator() ( int ) {} };      
      

we want the following expression to be true

    is_callable_with< A , int(void) >() == false; 
    is_callable_with< A , void(int) >() == true;  

Let's have a look at a simple test example:


  std::is_same<                                          
    void,                                                
    std::decltype( std::decval(A)()( std::declval(int) ) 
  >::value                                               

This expression evaluated to true if the class A is callable with signature void(int). How does this work? std::is_same tests if two types are the same.