Search code examples
c++c++11templatesenable-if

Calling std::to_string or std::to_wstring based on given typedef


In a library I am internally using typedefs of the following form:

using AnsiChar = char;
using WideChar = wchar_t;

A global typedef that basically stores the platform-specific char to be used in the entire library is defined like this:

// Either
using Char = AnsiChar;
// or
using Char = WideChar;
// depending on the platform this code is being compiled on

At some point in the code I want to either call std::to_string or std::to_wstring depending on the current Char type. My attempt looks like this:

template <typename TChar = Char, typename T>
typename std::enable_if<std::is_same<TChar, AnsiChar>::value, std::string>::type
ToString(const T& Arg)
{
    return std::to_string(Arg);
}

template <typename TChar = Char, typename T>
typename std::enable_if<std::is_same<TChar, WideChar>::value, std::wstring>::type
ToString(const T& Arg)
{
    return std::to_wstring(Arg);
}

Is this the correct way to implement a conditional function or is there any other way that is recommended to accomplish this?


EDIT. As a side-note I was considering to work with function pointers using something like std::basic_string<Char> as the return type to generalize this and then somehow conditionally bind either of std::to_string or std::to_wstring to the pointer.


Solution

  • template<class Char>
    struct string_traits;
    template<>
    struct string_traits<char>{
      using string=std::string;
      template<class T>
      static string convert_to_string(T&& t){
        using std::to_string;
        return to_string(std::forward<T>(t));
      }
    };
    template<>
    struct string_traits<wchar_t>{
      using string=std::wstring;
      template<class T>
      static string convert_to_string(T&& t){
        using std::to_wstring;
        return to_wstring(std::forward<T>(t));
      }
    };
    

    now your code is simply

    template <typename TChar = Char, typename T>
    std::basic_string<TChar>
    ToString(const T& Arg) {
      return string_traits<TChar>::convert_to_string(Arg);
    }