Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specialization of a template function with multiple template parameters in C++ 11

Cannot figure out why I am getting the compiler errors with the following code:

#include <tchar.h>

typedef TCHAR Char;

typedef std::basic_string<Char> String;

template<typename C, typename T>
std::basic_string<C> InternalToString(T val);

template<typename T>
inline std::string InternalToString<char, T>(T val)
{
    return std::to_string(val);
}

template<typename T>
inline std::wstring InternalToString<wchar_t, T>(T val)
{
    return std::to_wstring(val);
}

template<typename T>
inline String ToString(T val)
{
    return InternalToString<Char, T>(val);
}

if I compile the code with MSVC 2017 I get "error C2768: 'InternalToString': illegal use of explicit template arguments"

like image 526
Alexey Starinsky Avatar asked Jan 02 '23 00:01

Alexey Starinsky


1 Answers

Partial specialization is not allowed for function templates, it could be used only for class templates.

You can apply function templates overloading with SFINAE. e.g.

// used when C is specified as char
template<typename C, typename T>
inline typename std::enable_if<std::is_same<C, char>::value, std::string>::type InternalToString(T val)
{
    return std::to_string(val);
}

// used when C is specified as wchar_t
template<typename C, typename T>
inline typename std::enable_if<std::is_same<C, wchar_t>::value, std::wstring>::type InternalToString(T val)
{
    return std::to_wstring(val);
}

// used when C is specified as other types
template<typename C, typename T>
typename std::enable_if<!std::is_same<C, char>::value && !std::is_same<C, wchar_t>::value, std::basic_string<C>>::type InternalToString(T val);
like image 145
songyuanyao Avatar answered Jan 05 '23 15:01

songyuanyao