c++ - Printing textual representation of objects -
i'm relatively new c++. please excuse terminology if it's incorrect. tried searching around reply question, not find (probably because couldn't phrase question correctly). i'd appreciate if help me.
i trying write class creating strings might contain textual representation of objects or native types. essentially, have
private: stringstream ss; public: template< typename t > message& operator<<( const t& value ) { ss << value; homecoming *this; }
the overloaded << operator takes value , tries stream stringstream. think compiler fine if t
int
or if class t
defines method operator std::string()
. however, if t
type vector<int>
, no longer works because vector<int>
doesn't define operator std::string()
.
is there anyway perhaps overload operator if t
defines operator std::string()
, print textual representation, , if doesn't, print address?
thanks.
this can implemented building upon has_insertion_operator
type trait described here: http://stackoverflow.com/a/5771273/4323
namespace has_insertion_operator_impl { typedef char no; typedef char yes[2]; struct any_t { template<typename t> any_t( t const& ); }; no operator<<( std::ostream const&, any_t const& ); yes& test( std::ostream& ); no test( no ); template<typename t> struct has_insertion_operator { static std::ostream &s; static t const &t; static bool const value = sizeof( test(s << t) ) == sizeof( yes ); }; } template<typename t> struct has_insertion_operator : has_insertion_operator_impl::has_insertion_operator<t> { };
once have that, rest relatively straightforward:
class message { std::ostringstream ss; public: template< typename t > typename std::enable_if<has_insertion_operator<t>::value, message&>::type operator<<( const t& value ) { ss << value; homecoming *this; } template< typename t > typename std::enable_if<!has_insertion_operator<t>::value, message&>::type operator<<( const t& value ) { ss << &value; homecoming *this; } };
that is, if there insertion operator defined, print value, otherwise print address.
this not rely on conversion-to-std::string
operator beingness defined--you need create sure t
instances "printable" using operator <<
(typically implemented in same scope each t
defined, e.g. namespace or global scope).
c++ templates operator-overloading
No comments:
Post a Comment