Overriding multiple inherited templated functions with specialized versions

c++, multiple-inheritance, overriding, specialization, templates

Solution

Yes, you can make this work:

#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();
  }
}

Output:

Int callback for Derived1.
Float callback for Derived
Int callback for Derived2.
Float callback for Derived2

Problem

Okay, sample code first; this is my attempt at communicating what it is that I'm trying to do, although it doesn't compile: ``` #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"); } ``` So, what I'm trying to do is to make a sort of wrapper class to inherit from that will automatically connect the derived class to various callback lists; it needs to connect a specific instance of the derived class to the list, and I want the "user" to have / get to make the callback functions as part of making the derived class, as you can see. It seems like this should be able to work, although I may need to use a different syntax. If it can't work, do you have any suggestions?

Original source

Related problems