我是一名初学者 C++ 开发人员,我有一个关于通过模板进行操作员集成toString
的问题。ostream
我有这样的代码:
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;
}
代码编译无误,应用程序执行成功。使用这种方法好吗?我想在没有任何 boost 帮助的情况下实现它。