Deducing type when using a member function pointer as a template argument

When I want to have a member function as an argument to a template, is there a way to build it without providing a type Caller?

struct Foo
{
    template <typename Caller, void (Caller::*Func)(int)>
    void call(Caller * c) { (c->*Func)(6); }
};

struct Bar
{
    void start() 
    {
        Foo f;
        f.call<Bar, &Bar::printNumber>(this);
               ^^^^  
    }

    void printNumber(int i) { std::cout << i; }
};

int main ()
{
    Bar b;
    b.start();
    return 0;
}

when i try

template <void (Caller::*Func)(int), typename Caller>
void call(Caller * c) { (c->*Func)(6); }

and name it like

f.call<&Bar::printNumber>(this);

I get an error Caller is not class....

So, is there a way to let the compiler infer the type of Caller?

+3
source share
1 answer

No, not the way you want it. Callercan be inferred if

  • a pointer to a member function was a parameter, not a template parameter. For instance:

    template <class Caller>
    void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
    
  • it was known in advance. For example, you can make a call as follows:

    f.arg(this).call<&Bar::printNumber>();
    

    The function callwill look something like this:

    template <class Arg>
    struct Binder
    {
      template<void (Arg::*Func)(int)>
      void operator()() const {
        ...
      }
    };
    

    arg ( Binder<Bar>, Bar this).

    , .

+2

All Articles