C++ toString member-function and ostream operator << integration via templates -
i'm beginner c++ developer , have question tostring
, ostream
operator integration via templates. have such code:
struct methodcheckertypes{ typedef unsigned char truetype; typedef long falsetype; }; template<typename t>struct hastostring{ template<typename k>static typename methodcheckertypes::truetype test(decltype(&k::tostring)); template<typename> static typename methodcheckertypes::falsetype test(...); static const bool value = sizeof(test<t>(0)) == sizeof(typename methodcheckertypes::truetype); typedef decltype(test<t>(0)) valuetype; }; template<typename t, typename k> struct ifdef{}; template<> struct ifdef<typename methodcheckertypes::truetype, ostream&>{ typedef ostream& type; }; class withtostring{ public: string tostring() const{ return "hello"; } }; template<typename f, typename chart, typename traits> typename ifdef<typename hastostring<f>::valuetype, basic_ostream<chart, traits>&>::type operator<<(basic_ostream<chart, traits>& out, const f &ref){ out<<ref.tostring().c_str(); return out; } int main(int argc, char **argv){ withtostring hastostring; cout<<hastostring<<endl; return 0; }
the code has been compilled without errors, , application executed successfuly. use such approach? wanted implement without boost.
the approach implementing operator<<
normal. using parts of language not understand bad practice (i not believe beginner can write such code). have 2 alternatives: implement tostring
member function or overload operator<<(std::ostream&, t)
. latter approach enables use boost::lexical_cast
convert object string. me, latter approach more c++ish, if can without member function better so.
Comments
Post a Comment