Disambiguate overloaded member function pointer being passed as template parameter

后端 未结 1 1661
盖世英雄少女心
盖世英雄少女心 2020-12-01 06:24

I am attempting to recreate the Observer pattern where I can perfectly forward parameters to a given member function of the observers.

If I attempt

相关标签:
1条回答
  • 2020-12-01 06:43

    The issue is here:

    l.call(&foo::func, "hello");
    l.call(&foo::func, 0.5);
    

    For both lines, the compiler doesn't know which foo::func you are referring to. Hence, you have to disambiguate yourself by providing the type information that is missing (i.e., the type of foo:func) through casts:

    l.call(static_cast<void (foo::*)(const std::string&)>(&foo::func), "hello");
    l.call(static_cast<void (foo::*)(const double      )>(&foo::func), 0.5);
    

    Alternatively, you can provide the template arguments that the compiler cannot deduce and that define the type of func:

    l.call<void, const std::string&>(&foo::func, "hello");
    l.call<void, double            >(&foo::func, 0.5);
    

    Notice that you have to use double and not const double above. The reason is that generally double and const double are two different types. However, there's one situation where double and const double are considered as if they were the same type: as function arguments. For instance,

    void bar(const double);
    void bar(double);
    

    are not two different overloads but are actually the same function.

    0 讨论(0)
提交回复
热议问题