c++ - generic typetrait to convert to string or double -
i need type trait convert input string or double. have this:
template<typename t> struct sh_trait{ }; template<> struct sh_trait<float>{ typedef double type; }; template<> struct sh_trait<double>{ typedef double type; }; template<> struct sh_trait<char*>{ typedef std::string type; }; template<> struct sh_trait<const char*>{ typedef std::string type; }; template<std::size_t n> struct sh_trait<const char[n]> { typedef std::string type; }; template<std::size_t n> struct sh_trait<char[n]> { typedef std::string type; }; template<> struct sh_trait<std::string>{ typedef std::string type; }; template<> struct sh_trait<tstring>{ typedef std::string type; };
and using as
void f(t input) { sh_trait<t>::type myvalue(input); class template_class(myvalue); ... }
i doing because template_class specialized double
, string
.
the point is: suppose user use example int
. want convert double, have add line. possibile write more generic cover cases?
no c++11, no boost, c++03
you can implement base template has std::string
typedef. , can specialize other integral types using sfinae:
template <typename t, typename = void> struct sh_trait { typedef std::string type; }; template <typename t> struct sh_trait<t, typename std::enable_if<std::is_integral<t>::value>::type> { typedef double type; }; static_assert( std::is_same<sh_trait<int>::type, double>::value ); // doesn't run
Comments
Post a Comment