fork(2) download
  1. #include <type_traits>
  2. #include <utility>
  3.  
  4. template<typename T1, typename... Types>
  5. class Base
  6. {
  7. public:
  8. //assignment to base or derived class
  9. template<typename T, typename std::enable_if<std::is_base_of<Base<T1, Types...>, typename std::decay<T>::type>::value>::type* = nullptr>
  10. Base& operator=(T&& other)
  11. {
  12. if (this != &other)
  13. a = other.a;
  14. return *this;
  15. }
  16.  
  17. //assignment to other type contained in <T1, Types...>
  18. template<typename T, typename std::enable_if<!std::is_base_of<Base<T1, Types...>, typename std::decay<T>::type>::value>::type* = nullptr>
  19. Base& operator=(T&& other)
  20. {
  21. // do some stuff
  22. return *this;
  23. }
  24.  
  25.  
  26. private:
  27. int a;
  28. };
  29.  
  30. class Derived : public Base<int, double>
  31. {
  32. public:
  33. // similar pattern here, but call base class' operators
  34. // for both copy/move assignment
  35. // as well as assignment to int or double
  36. template<typename T>
  37. Derived& operator=(T&& other)
  38. {
  39. Base<int, double>::operator=(std::forward<T>(other));
  40. return *this;
  41. }
  42. };
  43.  
  44. int main() {
  45. Derived foo;
  46. int a = 4;
  47. foo = a;
  48. return 0;
  49. }
Success #stdin #stdout 0s 3336KB
stdin
Standard input is empty
stdout
Standard output is empty