相关疑难解决方法(0)

是否可以编写模板来检查函数的存在?

是否可以编写一个模板来改变行为,具体取决于是否在类上定义了某个成员函数?

这是我想写的一个简单例子:

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"部分.

c++ templates sfinae template-meta-programming

458
推荐指数
20
解决办法
14万
查看次数

Pretty-print C++ STL containers

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)

c++ templates operator-overloading pretty-print c++11

379
推荐指数
5
解决办法
4万
查看次数

如何正确实现自定义迭代器和const_iterators?

我有一个自定义容器类,我想写它iteratorconst_iterator类.

我之前从未这样做过,但我找不到合适的方法.关于迭代器创建的指导原则是什么,我应该注意什么?

我也想避免代码重复(我觉得const_iteratoriterator分享很多东西;应该是另一个子类吗?).

脚注:我很确定Boost有什么可以缓解的,但我不能在这里使用它,因为很多愚蠢的原因.

c++ iterator const-iterator

217
推荐指数
8
解决办法
17万
查看次数