Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"multiple overloads" using templated class with duplicate types

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!

like image 529
Sam P Avatar asked Sep 22 '18 16:09

Sam P


1 Answers

How about a specialization:

template <typename T>
class BinaryObserver<T, T> : public IObserver<T> {
 public:
  void Next(const T & value) noexcept override{};
};
like image 99
user7860670 Avatar answered Sep 30 '22 13:09

user7860670