How to specialize a template member function in a template class in C ++?

As for this question: How to create specialization for one method in a template class in C ++? ...

I have this class:

template <typename T> class MyCLass { public: template <typename U> U myfunct(const U& x); }; // Generic implementation template <typename T> template <typename U> U MyCLass<T>::myfunct(const U& x) {...} 

And I want to specialize myfunct for double s.

This is what I do:

 // Declaring specialization template <> template <typename T> double MyCLass<T>::myfunct(const double& x); // Doing it template <> template <typename T> double MyCLass<T>::myfunct(const double& x) {...} 

But that will not work.

+1
source share
1 answer

This is not possible in C ++. You can only specialize a member function template if you also specialize in all closing class templates.

But in any case, it is usually better to overload function templates rather than specializing in them (for details, see the article in the article by Herb Sutter ). So just do it:

 template <typename T> class MyCLass { public: template <typename U> U myfunct(const U& x); double myfunct(double x); }; 
+3
source

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


All Articles