user152508
user152508

Reputation: 3141

boost function to any functor with template operator ()

I want to store boost::function<void(void*)> in order to point to an arbitrary functor class object. I tried the following code, but it does not compile :

struct MyFunctor
{
    template<class T>
    void operator()(T* a)
    {            
        T& ref = *a; 

    } 
};
struct MyFunctor2
{
    template<class T>
    void operator()(T* a)
    {            
        T& ref = *a; 

    } 
};

boost::function<void(void*)> anyFunctorPtr;
anyFunctorPtr= MyFunctor();
double a = 5;   
anyFunctorPtr(&a);

The compiler error is error C2182: 'ref' : illegal use of type 'void'

Upvotes: 0

Views: 377

Answers (1)

Max Langhof
Max Langhof

Reputation: 23711

boost::function, just like std::function requires a specific functor signature (in your case void(void*)), which is the signature it will try to call your functor with. That's why T is deduced as void and the compiler refuses to give you a void&, rightfully so.

Your example is fundamentally add odds with itself, because if you want to have type erasure, you cannot have templates, as the compiler cannot know which templates to instantiate otherwise. Assume for a moment that boost::function<magic> could do what you want.

If you give the compiler code like this:

void foo(boost::function<magic> func)
{
    double a = 5;   
    func(&a);
}

How would the compiler know whether to generate a T = double instantiation for MyFunctor or MyFunctor2? It simply cannot know, and thus it cannot generate the right code. There is no limit on the amount of templated functor classes you can have and the number of types you can attempt to call operator() with, so instantiating them automatically ahead of time is also out of the question.

Upvotes: 2

Related Questions