定义泛型比较运算符 [英] Define generic comparison operator

查看:101
本文介绍了定义泛型比较运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 <$ c $ 

我想出了一个想法来定义一个通用的比较运算符,它可以处理任何类型的数据。 c> #include< cstring>
#include< iostream>

class A
{
public:
A(int id):id(id){}
$ b private:
int id;
};

模板< class T>
inline bool operator ==(const T& a,const T& b)
{
return memcmp(& a,& b,sizeof(a))== 0; //执行不重要(可能由于填充而失败)
}

int main()
{
std :: cout<< (A(10)== A(10))<的std :: ENDL; // 1
std :: cout<< (A(10)== A(15))的std :: ENDL; // 0
}

我认为这可能有助于避免缺省的缺省比较运算符在c ++中。



这是一个糟糕的主意吗?我不知道这样做是否会在某些情况下破坏任何东西? 解决方案

b
$ b

如果某些类型没有定义相等运算符,很可能是因为您无法合理比较该类型的两个对象是否相等。



<即使对于缺失的等式操作符被实现者忽略的情况,任何你会想到的全部捕获实现都很不可能做到合理。†因此得出结论:不要这样做!编译时间错误比运行时错误要好;而不是过早地添加一个隐藏实际问题的最可靠的解决方案,在编译时错误发生时添加实际解决方案。




<对于初学者来说,你想出的解决方案对于带有填充的类型,带有重载的一元运算符& 的类型以及任何类型一些指针或引用像成员;甚至可以与任何上述类别的任何成员或基础进行分类。所以,对于一个的东西。


I came up with the idea to define a generic comparison operator which would work with any type, for the fun of it.

#include <cstring>
#include <iostream>

class A
{
    public:
        A(int id) : id(id) {}

    private:
        int id;
};

template <class T>
inline bool operator==(const T& a, const T& b)
{
    return memcmp(&a, &b, sizeof(a)) == 0; // implementation is unimportant (can fail because of padding)
}

int main()
{
    std::cout << (A(10) == A(10)) << std::endl; // 1
    std::cout << (A(10) == A(15)) << std::endl; // 0
}

I think this could be useful to get around the lack of default comparison operator in c++.

Is this a terrible idea? I wonder if doing this could break anything in some circumstances?

解决方案

Doing this is indeed a terrible idea.

If some type does not define an equality operator, it is most likely because you cannot reasonably compare two objects of that type for equality.

Even for the case where the missing equality operator was an oversight by the implementer, any "catch-all" implementation you would come up with is highly unlikely to do something sensible.

So to conclude: Don't do this! Compile time errors are better than runtime errors; instead of prematurely adding a most certainly broken "solution" hiding the actual problem, add actual solutions as the compile time errors occur.


For starters, the solution you came up with fails for types with padding, types with overloaded unary operator&, and any type that has some pointer or reference like member; or even types with any member or base of any of the aforementioned categories. So for a ton of stuff.

这篇关于定义泛型比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆