调用模板化基类函数的函数引用

时间:2017-06-01 09:17:05

标签: c++ templates inheritance reference callback

我很难理解为什么我不能调用对基类函数的引用。如果你们有一些想法,请与我分享。代码中有更多解释。这只是我尝试做的事情的一种表示,因为我使用了boost并且代码太长了。

rextester中的实时样本:http://rextester.com/live/QRJHPL54630

//g++  5.4.0

#include <iostream>

//have a base class which calls a function from the derived template
template<typename Derived>
struct Base
{
    template<void (Derived::*action)(void)>
    void callMethod(Derived& d)
    {
        (d.*action)();
    }
};

struct Evt
{
    void evt_doSmth(){ std::cout << "finally" << std::endl; };    
};


struct Foo : public Base<Foo>, public Evt
{
    void foo_doSmth(){ std::cout << "i expected this" << std::endl; };    
};

int main()
{
    Foo f;

    //this works because the function in declared in the Foo class
    f.callMethod<&Foo::foo_doSmth>(f);
    f.foo_doSmth();

    //i don't understand why this is not working, because the function
    //should be accessible from the Foo class since it inherits Evt class
    //could not convert template argument.

    f.callMethod<&Foo::evt_doSmth>(f);//<------- this does not work.

    f.evt_doSmth(); // works obviously
}

0 个答案:

没有答案