C++确定类是否具有可比性

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)

谢谢你的帮助!

Ben*_*igt 15

C++模板是duck-typed,因此不需要接口或约束,编译器将使用比较运算符(如果存在),如果不存在则生成错误.

另见这个更详细的答案.


Mat*_*att 5

如果你想避免神秘错误(正如你经常在模板实例化树中发生缺乏可比性时那样),只需使用enable_if:

特别是,请看一下boost :: enable_if的文档中的"启用模板类特化".

您经常使用带有type_traits的enable_if:http://www.boost.org/doc/libs/release/libs/type_traits/doc/html/index.html

您的案例中特别感兴趣的可能是以下几点:

http://www.boost.org/doc/libs/release/libs/type_traits/doc/html/boost_typetraits/reference:/has_equal_to.html

http://www.boost.org/doc/libs/release/libs/type_traits/doc/html/boost_typetraits/reference/has_not_equal_to.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/

http://neoscientists.org/~tschwinger/boostdev/concept_traits/libs/concept_traits/doc/#StandardConceptTraits

但是,它似乎被放弃了: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