samedi 22 septembre 2018

"multiple overloads" with templated class

I'm trying to write a class that takes two templated types. This class inherits from an interface. See the below code.

#include <iostream>
#include <string>

template <typename T>
class IObserver {
 public:
  virtual void Next(const T& value) noexcept = 0;
};

template <typename T1, typename T2>
class BinaryObserver : public IObserver<T1>, public IObserver<T2> {
 public:
  void Next(const T1& value) noexcept override{};

  void Next(const T2& value) noexcept override{};
};

int main() {
  // This is OK
  BinaryObserver<int, float> mc1;
  mc1.Next(0);
  mc1.Next(0.0f);

  // This fails to compile with "multiple overloads"
  BinaryObserver<int, int> mc2;
  mc2.Next(0);
  mc2.Next(0);
}

I'm having trouble when T1 is the same type as T2. Obviously this means two Next functions will be generated with the same type, which gives an error: multiple overloads of 'Next' instantiate to the same signature.

What's an idiomatic way of fixing this? I'm not sure how to handle the case when T1=T2 since I'd only need one Next function generated

Thanks!

Aucun commentaire:

Enregistrer un commentaire