How to specialize a C ++ template function based on a type dependent on a type?

I have a template with C ++ templates

// Definition
template <typename T>
class MyCLass {
public:
  typedef typename T::S MyS; // <-- This is a dependent type from the template one
  MyS operator()(const MyS& x);
};

// Implementation
template <typename T>
MyCLass<T>::MyS MyClass<T>::operator()(const MyClass<T>::MyS& x) {...}

I want the overloaded operator operator()to behave differently when MySthere is one double.

I was thinking about specialization, but how to do this in this case, given that specialization should act on a type-dependent type? Thankyou

+4
source share
2 answers

You can redirect work to some private overloaded function:

template <typename T>
class MyCLass {
public:
  typedef typename T::S MyS;
  MyS operator()(const MyS& x) { return operator_impl(x); }

private:
  template<typename U>
  U operator_impl(const U& x);

  double operator_impl(double x);
};
+3
source

You can solve this problem by entering an additional default parameter:

template <typename T, typename Usual = typename T::S>
class MyClass { ... };

Then you can specialize in double:

template <typename T>
class MyClass<T, double> { ... }
+3

Source: https://habr.com/ru/post/1502555/


All Articles