user1633272 user1633272 - 1 year ago 161
C++ Question

How to declare specialization template method outside class?

The Converter class is designed to convert a string into another type. So if the target is also a string, then it should just return copy of the original value.

The working code is like this:

template<typename C>
class Converter {
public:
template<typename T>
static T To(const std::wstring& obj);

template<>
static std::wstring To(const std::wstring& obj) {
return obj;
}
};

template<typename C>
template<typename T>
T Converter<C>::To(const std::wstring& obj) {
// Conversion
return T();
}


(Works on VC++2015 Update 3)

I tried to move the specialization method outside the class declaration like this:

template<typename C>
template<>
std::wstring Converter<C>::To<std::wstring>(const std::wstring& obj) {
return obj;
}


And there are several compilation errors:


Error C3212 'Converter::To': an explicit specialization of a
template member must be a member of an explicit specialization

Error C2768 'Converter::To': illegal use of explicit template
arguments

Answer Source

Rule of thumb:

prefer function overload over specialization!

In your case use overload and sfinae:

#include <type_traits>
#include <string>

template<typename C>
class Converter {
public:
    template<typename T, typename std::enable_if<!std::is_same<T, std::wstring>::value>::type* = nullptr >
    static T To(const std::wstring& obj) {

    }

    template<typename T, typename std::enable_if<std::is_same<T, std::wstring>::value>::type* = nullptr >
    static std::wstring To(const std::wstring& obj) {

    }
};

[live demo]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download