如何检查operator==是否存在?
我正在尝试创建一个示例,它将检查 operator==
(成员或非成员函数)是否存在。检查一个类是否有成员operator==
很容易,但是如何检查它是否有非成员operator==
呢?
这就是我到目前为止所要做的:
#include <iostream>
struct A
{
int a;
#if 0
bool operator==( const A& rhs ) const
{
return ( a==rhs.a);
}
#endif
};
#if 1
bool operator==( const A &l,const A &r )
{
return ( l.a==r.a);
}
#endif
template < typename T >
struct opEqualExists
{
struct yes{ char a[1]; };
struct no { char a[2]; };
template <typename C> static yes test( typeof(&C::operator==) );
//template <typename C> static yes test( ???? );
template <typename C> static no test(...);
enum { value = (sizeof(test<T>(0)) == sizeof(yes)) };
};
int main()
{
std::cout<<(int)opEqualExists<A>::value<<std::endl;
}
是否可以编写一个测试函数来测试非成员 operator==
是否存在?
如果是,怎么办?
顺便说一句,我检查过类似的问题,但没有找到合适的解决方案:
是否可以使用 SFINAE /templates 检查运算符是否存在?
这是我尝试过的:
template <typename C> static yes test( const C*,bool(*)(const C&,constC&) = &operator== );
但是如果删除非成员运算符 == 则编译失败
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
C++03
以下技巧有效,可用于所有此类运算符:
用法:
第二个
template typename Arg
对于某些特殊情况很有用,例如A::operator==(short )
,它与class
本身并不相似。在这种情况下,用法是:演示。
C++11
当我们有
decltype
和std::declval
时,我们不需要使用sizeof
和空引用技巧演示
C++03
The following trick works and it can be used for all such operators:
Usage:
The 2nd
template typename Arg
is useful for some special cases likeA::operator==(short)
, where it's not similar toclass
itself. In such cases the usage is:Demo.
C++11
We need not use
sizeof
and null reference trick when we havedecltype
andstd::declval
Demo
查看 Boost 的概念检查库 (BCCL) http: //www.boost.org/doc/libs/1_46_1/libs/concept_check/concept_check.htm。
它使您能够编写类必须匹配的要求才能编译程序。你可以相对自由地检查什么。例如,验证类 Foo 的
operator==
是否存在将编写如下:只要
operator==
的两个实现之一是,此代码就可以正常编译。可用的。按照 @Matthieu M. 和 @Luc Touraille 的建议,我更新了代码片段以提供
boost::EqualityComparable
用法的示例。再次请注意,EqualityComparable 也会强制您声明operator!=
。Have a look at Boost's Concept Check Library (BCCL) http://www.boost.org/doc/libs/1_46_1/libs/concept_check/concept_check.htm.
It enables you to write requirements that a class must match in order for the program to compile. You're relatively free with what you can check. For example, verifying the presence of
operator==
of a class Foo would write as follow:This code compiles fine as long as one of the two implementations of
operator==
is available.Following @Matthieu M. and @Luc Touraille advice, I updated the code snippet to provide an example of
boost::EqualityComparable
usage. Once again, please note that EqualityComparable forces you to declareoperator!=
too.也可以仅使用 c++11 类型特征来检查成员是否存在:
您可以像这样使用特征:
has_operator_equal
的结果类型将是std::true_type
或std::false_type
(因为它继承自std::is_same::type
的别名),并且都定义了一个静态值 成员,它是一个布尔值。
如果您希望能够测试您的类是否定义了
operator==(someOtherType)
,您可以设置第二个模板参数:其中模板参数
MyClass
仍然是类您正在测试operator==
是否存在,而long
是您希望能够进行比较的类型,例如测试MyClass 有
operator==(long)
。如果
EqualTo
(就像第一个示例中那样)未指定,它将默认为T
,导致operator==(MyClass) 的正常定义
。注意事项:在
operator==(long)
的情况下,此特征对于long
或隐式任何值都为 true可转换为long
,例如double
、int
等。您还可以定义对其他运算符和函数的检查,只需替换
decltype
里面有什么。要检查!=
,只需替换为
It's also possible to use only c++11 type traits to check the existence of the member:
You can use the trait like so:
The resulting type of
has_operator_equal
will either bestd::true_type
orstd::false_type
(because it inherits from an alias ofstd::is_same::type
), and both define a staticvalue
member which is a boolean.If you want to be able to test whether your class defines
operator==(someOtherType)
, you can set the second template argument:where the template parameter
MyClass
is still the class that you are testing for the presence ofoperator==
, andlong
is the type you want to be able to compare to, e.g. to test thatMyClass
hasoperator==(long)
.if
EqualTo
(like it was in the first example) is left unspecified, it will default toT
, result in the normal definition ofoperator==(MyClass)
.Note of caution: This trait in the case of
operator==(long)
will be true forlong
, or any value implicitly convertible tolong
, e.g.double
,int
, etc.You can also define checks for other operators and functions, just by replacing what's inside the
decltype
. To check for!=
, simply replacewith
C++20
我猜你想检查用户提供的类型是否有相等运算符;如果是这种情况,Concepts 将为您提供帮助。
如果您传递任何未定义
==
和!=
的类型,编译器只会出错并显示消息,例如:您还可以使用
std::equality_comparable_with
概念来检查两种不同类型之间的重载。标准中添加了更多概念,例如 std::incrementable 等。请查看 标准库概念作为一个很好的起点。
C++20
I guess you want to check whether a user-provided type has equality operator or not; if that is the case then Concepts are here to help.
If you pass any type that does not have
==
and!=
defined, the compiler just errors out with message, e.g.:You can also use
std::equality_comparable_with<T, U>
concept to check for those overload between two different types.There are many more concepts that have been added to standards such as
std::incrementable
etc.. Have a look at Standard Library concepts as a good starting point.从 c++14 开始,标准二进制函数为我们的大多数运算符完成了大部分工作。
As of c++14, the standard binary functions do most of the work for us for the majority of operators.
我知道这个问题早已得到解答,但我认为对于将来发现这个问题的任何人来说,Boost 刚刚在其 type_traits 库中添加了一堆“has 运算符”特征,其中包括 has_equal_to,它满足了OP的要求。
I know this question has long since been answered but I thought it might be worth noting for anyone who finds this question in the future that Boost just added a bunch of "has operator" traits to their type_traits library, and among them is has_equal_to, which does what OP was asking for.
这个问题已经被回答过几次了,但是有一种更简单的方法来检查
operator==
或基本上任何其他操作是否存在(例如,测试具有特定名称的成员函数),通过将decltype
与,
运算符一起使用:您可以使用相同的方法来检查类型
T
是否具有成员函数foo
可以使用特定的参数列表调用:我认为这使得代码的意图更加清晰。除此之外,这是一个 C++11 解决方案,因此它不依赖于任何较新的 C++14 或 C++17 功能。当然,最终结果是相同的,但这已成为我测试此类事物的首选习惯用法。
编辑:修复了重载逗号运算符的疯狂情况,我总是想念这一点。
This question has already been answered several times, but there is a simpler way to check for the existence of
operator==
or basically any other operation (e.g., testing for a member function with a certain name), by usingdecltype
together with the,
operator:You can use this same approach to check if a type
T
has a member functionfoo
which is invocable with a certain argument list:I think this makes the intent of the code much clearer. In addition to that, this is a C++11 solution, so it doesn't depend on any newer C++14 or C++17 features. The end result is the same, of course, but this has become my preferred idiom for testing these kinds of things.
Edit: Fixed the insane case of the overloaded comma operator, I always miss that.
c++17 稍作修改的 Richard Hodges 版本 godbolt
c++17 slightly modified version of Richard Hodges godbolt
让我们考虑以下形式的元函数,它检查给定类型是否存在相等运算符(即
==
):但是,这对于某些极端情况可能不够好。例如,假设您的类
X
确实定义了operator==
但它不返回bool
,而是返回Y
代码>.那么在这种情况下,equality::value
应该返回什么?真
还是假
?好吧,这取决于我们现在不知道的具体用例,并且假设任何事情并将其强加给用户似乎不是一个好主意。但是,一般来说,我们可以假设返回类型应该是bool
,因此让我们在接口本身中表达这一点:R
的默认值是bool
code> 表示这是一般情况。如果operator==
的返回类型不同,例如Y
,那么您可以这样说:它也会检查给定的返回类型。默认情况下,
这是此元功能的一种实现:
测试:
输出:
在线演示
希望有帮助。
Lets consider a meta-function of the following form, which checks for the existence of equality operator (i.e
==
) for the given type:However, that might not be good enough for some corner cases. For example, say your class
X
does defineoperator==
but it doesn't returnbool
, instead it returnsY
. So in this case, what shouldequality<X>::value
return?true
orfalse
? Well, that depends on the specific use case which we dont know now, and it doesn't seem to be a good idea to assume anything and force it on the users. However, in general we can assume that the return type should bebool
, so lets express this in the interface itself:The default value for
R
isbool
which indicates it is the general case. In cases, where the return type ofoperator==
is different, sayY
, then you can say this:which checks for the given return-type as well. By default,
Here is one implementation of this meta-function:
Test:
Output:
Online Demo
Hope that helps.
除了@coder3101答案之外,
concepts
还可以帮助您实现您想要的任何功能存在测试。例如,std::equality_comparable
是使用 4 个简单测试来实现的,这些测试检查以下场景:对于
A
和B
变量,请确保以下表达式是有效的:如果其中任何一个在编译时非法,则程序将无法编译。此测试的实施(从标准简化):
如您所见,您可以自定义此概念并创建您自己的概念来满足您的条件。例如,如果您只想强制
operator==
存在,则可以执行以下操作:阅读有关 C++20 中
概念
的更多信息。In addition to @coder3101 answer,
concepts
can help you implement any function existence tests you want to. For example,std::equality_comparable
is implemented using 4 simple tests, that check the following scenarios:For
A
andB
variables, make sure that the following expressions are valid:If any one of them is illegal at compile time, the program won't compile. The implementation of this test (simplified from the standard):
As you can see, you can customize this concept and create your own concept the fulfill your conditions. For example, if you want to force only the existence of
operator==
, you can do something like this:Read more about
concepts
in C++20.如果我们想测试二元运算符(或其他二元函子),我们可以使用 std::equal_to (或任何其他重载的结构成员)来制定更通用的解决方案。
用法:
We can use
std::equal_to<Type>
(or any other overloaded struct members) to make a more generic solution if we want to test binary operators (or other binary functors).Usage:
这应该适用于 C++11
This should work on C++11
仅供参考,我发布了如何解决问题的方法,无需检查
operator==
是否存在:Just for a reference, I am posting how I solved my problem, without a need to check if the
operator==
exists :IMO,这必须是类本身的一部分,因为它处理类的私有属性。模板在编译时被解释。默认情况下,它生成
operator==
、构造函数、析构函数和复制构造函数,它们对相同类型的对象进行按位复制(浅复制)或按位比较。特殊情况(不同类型)必须重载。如果您使用全局运算符函数,则必须将该函数声明为友元才能访问私有部分,否则您必须公开所需的接口。有时这真的很难看,可能会导致不必要的函数暴露。IMO, this must be part of the class itself as it's deals with the private attributes of the class. The templates are interpreted at compile time. By default it generates
operator==
,constructor, destructor and copy constructor which do bit-wise copy (shallow copy) or bit-wise comparisons for the object of same type. The special cases (different types) must be overloaded. If you use global operator function you will have to declare the function as friend to access the private part or else you've to expose the interfaces required. Sometimes this is really ugly which may cause an unnecessary expose of a function.