Jaa*_*a-c 11 c++ generics templates comparable
我或多或少是Java程序员,所以这可能是一个愚蠢的问题,但我找不到任何简单的解决方案.
我在C++中有这样的类:
template<class T> class Node {...}
Run Code Online (Sandbox Code Playgroud)
我需要T才能具有可比性 - 至少要定义== <>运算符.有没有简单的方法来做到这一点 - 或者最佳做法是什么?在Java中,它将是这样的:
public class Node<T extends Comparable> { ... }
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
如果你想避免神秘错误(正如你经常在模板实例化树中发生缺乏可比性时那样),只需使用enable_if:
如果你有C++ 98或C++ 03编译器,那么boost :: enable_if:http://www.boost.org/doc/libs/release/libs/utility/enable_if.html
如果你有C++ 11编译器,std :: enable_if:http://en.cppreference.com/w/cpp/types/enable_if
特别是,请看一下boost :: enable_if的文档中的"启用模板类特化".
您经常使用带有type_traits的enable_if:http://www.boost.org/doc/libs/release/libs/type_traits/doc/html/index.html
您的案例中特别感兴趣的可能是以下几点:
但是请参阅has_greater,has_greater_equal,has_less,has_less_equal等等.//实际上有点惊讶的是没有一个简单的is_equality_comparable类型特征.
//编辑:看来我已经找到了它,它是概念特征库中的:: boost :: is_equality_comparable :: value:http://neoscientists.org/~tschwinger/boostdev/concept_traits/libs/concept_traits/doc/
但是,它似乎被放弃了:https://svn.boost.org/trac/boost/wiki/LibrariesUnderConstruction#Boost.ConceptTraits
另一种解决方案是使用Boost概念检查库(BCCL),特别是应用EqualityComparableConcept:
http://www.boost.org/doc/libs/release/libs/concept_check/using_concept_check.htm
另一种选择:Boost.Generic - https://svn.boost.org/trac/boost/wiki/LibrariesUnderConstruction#Boost.Generic
Prensentation:http://github.com/boostcon/2011_presentations/raw/master/thu/Boost.Generic.pdf
另一种选择:http: //code.google.com/p/origin/source/browse/trunk/core/tests/concepts/equality_comparable.cpp