如何检查operator ==是否存在? [英] How to check whether operator== exists?
问题描述
我试图创建一个例子,它将检查运算符==
(成员或非成员函数)的存在。要检查类是否有成员 operator ==
很容易,但如何检查它是否有一个非成员运算符==
?
I am trying to create an example, which would check the existence of the operator==
(member or, non-member function). To check whether a class has a member operator==
is easy, but how to check whether it has a non-member 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 ==
?
如果是,如何?
Is it possible to write a test function to test the existence of non-member operator==
?
If yes, how?
btw我已检查过类似问题,但没有找到正确的解决方案:
是否可以使用SFINAE /模板检查操作员是否存在?
btw I have checked similar questions, but haven't found a proper solution :
Is it possible to use SFINAE/templates to check if an operator exists?
这是我试过的:
template <typename C> static yes test( const C*,bool(*)(const C&,constC&) = &operator== );
但是如果非成员运算符==被删除,编译失败
but the compilation fails if the non-member operator== is removed
推荐答案
C ++ 03
它可以用于所有这样的运算符:
C++03
Following trick works. And it can be used for all such operators:
namespace CHECK
{
class No { bool b[2]; };
template<typename T, typename Arg> No operator== (const T&, const Arg&);
bool Check (...);
No& Check (const No&);
template <typename T, typename Arg = T>
struct EqualExists
{
enum { value = (sizeof(Check(*(T*)(0) == *(Arg*)(0))) != sizeof(No)) };
};
}
用法:
CHECK::EqualExists<A>::value;
第二个模板类型名Arg
一些特殊情况如 A :: operator ==(short)
,其中不像 class
本身。在这种情况下,用法是:
The 2nd template typename Arg
is useful for some special cases like A::operator==(short)
, where it's not similar to class
itself. In such cases the usage is:
CHECK::EqualExists<A, short>::value
// ^^^^^ argument of `operator==`
演示。
当我们有 decltype
>时,我们不必使用 sizeof
p>
We need not use sizeof
trick when we have decltype
namespace CHECK
{
struct No {};
template<typename T, typename Arg> No operator== (const T&, const Arg&);
template<typename T, typename Arg = T>
struct EqualExists
{
enum { value = !std::is_same<decltype(*(T*)(0) == *(Arg*)(0)), No>::value };
};
}
这篇关于如何检查operator ==是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!