Andry
Andry

Reputation: 16845

How to specialize a C++ templated-class function basing on a type-dependent type?

I have a C++ templated class

// 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) {...}

What I want is that overloaded operator operator() behaves differently when MyS is double.

I thought about specialization, but how to do in this case considering that the specialization should act on a type-dependent type? Thankyou

Upvotes: 4

Views: 129

Answers (2)

Yuushi
Yuushi

Reputation: 26040

You can solve this by introducing an extra default parameter:

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

Then you can specialize using a double:

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

Upvotes: 3

jrok
jrok

Reputation: 55395

You could forward the 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);
};

Upvotes: 3

Related Questions