Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

c++ - Deducing type, when using member function pointer as template argument

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

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 call it like

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

I am getting Caller is not class... error.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, not as you want it. Caller could be deduced if

  1. the pointer to member function were an parameter, not a template parameter. Eg:

    template <class Caller>
    void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
    
  2. it was known beforehand. For example, you could make the call look like this:

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

    The call function would look similar to this:

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

    The arg function would be easy to write (in your case it would return Binder<Bar>, where Bar is deduced from this).

    Not very convenient, IMHO.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...