是否可以编写一个模板来改变行为,具体取决于是否在类上定义了某个成员函数?
这是我想写的一个简单例子:
template<class T>
std::string optionalToString(T* obj)
{
if (FUNCTION_EXISTS(T->toString))
return obj->toString();
else
return "toString not defined";
}
Run Code Online (Sandbox Code Playgroud)
所以,如果class T
已经toString()
确定的话,就使用它; 否则,它没有.我不知道怎么做的神奇部分是"FUNCTION_EXISTS"部分.
Please take note of the updates at the end of this post.
Update: I have created a public project on GitHub for this library!
I would like to have a single template that once and for all takes care of pretty-printing all STL containers via operator<<
. In pseudo code, I'm looking for something like this:
template<container C, class T, String delim = ", ", String open = "[", String close = "]">
std::ostream & operator<<(std::ostream & o, const C<T> …
Run Code Online (Sandbox Code Playgroud) 我有一个自定义容器类,我想写它iterator
和const_iterator
类.
我之前从未这样做过,但我找不到合适的方法.关于迭代器创建的指导原则是什么,我应该注意什么?
我也想避免代码重复(我觉得const_iterator
并iterator
分享很多东西;应该是另一个子类吗?).
脚注:我很确定Boost有什么可以缓解的,但我不能在这里使用它,因为很多愚蠢的原因.