使用专用版本覆盖多个继承的模板化函数

Nar*_*tor 5 c++ templates overriding multiple-inheritance specialization

好的,首先是示例代码; 这是我尝试传达我正在尝试做的事情,尽管它没有编译:

#include <iostream>

template <class T>
class Base
{
public:
    virtual void my_callback() = 0;
};

class Derived1
    : public Base<int>
    , public Base<float>
{
public:
    void my_callback<int>()
    {
        cout << "Int callback for Derived1.\n";
    }
    void my_callback<float>()
    {
        cout << "Float callback for Derived\n";
    }
};

class Derived2
    : public Base<int>
    , public Base<float>
{

public:
    void my_callback<int>()
    {
        cout << "Int callback for Derived2.\n";
    }
    void my_callback<float>()
    {
        cout << "Float callback for Derived2\n";
    }

};

int main()
{
    {
        Derived1 d;
        Base<int> * i_p = d;
        Base<float> * i_f = d;

        i_p->my_callback();
        i_f->my_callback();
    }
    {
        Derived2 d;
        Base<int> * i_p = d;
        Base<float> * i_f = d;

        i_p->my_callback();
        i_f->my_callback();
    }

    //Desired output:
    // Int callback for Derived1.
    // Float callback for Derived1
    // Int callback for Derived2.
    // Float callback for Derived2
    system("Pause");
}
Run Code Online (Sandbox Code Playgroud)

所以,我正在尝试做的是使一种包装类继承,它会自动将派生类连接到各种回调列表; 它需要将派生类的特定实例连接到列表,并且我希望"user"具有/ get来使回调函数作为创建派生类的一部分,如您所见.

看起来这应该可以工作,虽然我可能需要使用不同的语法.如果它无法工作,你有什么建议吗?

Han*_*ant 2

是的,你可以做到这一点:

#include <iostream>
using namespace std;

template <class T>
class Base
{
public:
  virtual void my_callback() = 0;
};

class Derived1 : public Base<int>, public Base<float>
{
public:
  void Base<int>::my_callback() {
    cout << "Int callback for Derived1.\n";
  }
  void Base<float>::my_callback() {
    cout << "Float callback for Derived\n";
  }
};

class Derived2 : public Base<int>, public Base<float>
{
public:
  void Base<int>::my_callback() {
    cout << "Int callback for Derived2.\n";
  }
  void Base<float>::my_callback() {
    cout << "Float callback for Derived2\n";
  }
};

int main()
{
  {
    Derived1 d;
    Base<int> * i_p = &d;
    Base<float> * i_f = &d;
    i_p->my_callback();
    i_f->my_callback();
  }
  {
    Derived2 d;
    Base<int> * i_p = &d;
    Base<float> * i_f = &d;
    i_p->my_callback();
    i_f->my_callback();
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Int callback for Derived1.
Float callback for Derived
Int callback for Derived2.
Float callback for Derived2
Run Code Online (Sandbox Code Playgroud)