【发布时间】:2011-04-29 11:22:44
【问题描述】:
我是一名初学者 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 帮助的情况下实现它。
【问题讨论】:
-
你是一个初学者并从一开始就开始使用模板(C++最危险的特性)?
-
你似乎是一个非常进步的初学者。 :) 进展顺利。
-
谢谢。我想说我是初学者模板开发人员。而且这段代码sn-p使用了C++0x特性(decltype)。
-
这个问题可能更适合 codereview.stackexchange.com
标签: c++ templates c++11 ostream sfinae