sfinae - Check for existence of global operator<< in C++ -
hello want write 2 implementations of to_string member function follows:
template <typename t0> class foo { public: std::string to_string(); public: t0 m_value; }; template <typename t0> std::string foo<t0>::to_string() { std::stringstream ss; ss << m_value; return ss.str(); } template <typename t0> std::string foo<t0>::to_string() { return typeid(t0).name(); }
i have seen this, don't know how use code, i'm not used enable_if , boost mpl @ all. how should define 2 to_string functions use second fallback?
thanks.
my take on this: can take metafunction found is, works nicely. let's still discuss briefly why working:
sizeof
not evaluate expression; deduces type , returns size of type. type sizes implementation defined , cannot assume them, know sizeof(char) != sizeof(char[2])
, use these types test for.
we define stream operator @ namespace level using any_t
type, accept - guessed - type , let return (it's not important type, long it's not ostream &
). fall if type not have stream operator defined. in class define 2 functions, 1 taking ostream &
, result if stream operator defined, , 1 taking return type defined our fallback function.
we can test sizeof(test(s << c))
which, again, not evaluate expression, determine return type , return size.
now understand how works, there's left embed our application. there several approaches this; 1 way, works prior c++11 use functor:
template <bool, typename t> struct to_string_functor { std::string operator()(t const & t) const { std::stringstream ss; ss << t; return ss.str(); } }; template <typename t> struct to_string_functor<false, t> { std::string operator()(t const &) const { return typeid(t).name(); } }; template <typename t> struct foo { std::string to_string() const { return to_string_functor< has_insertion_operator<t>::value, t >()(m_value); } /* ... */ };
there more ways this, 1 being enable_if
, if c++11 available (you want partially specialized functions this); may want read this excellent blog post on matter.
in simple case however, functor should in opinion.
Comments
Post a Comment