加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 这是一个安全的方法来实现一个通用的operator ==和operator

发布时间:2020-12-16 05:41:51 所属栏目:百科 来源:网络整理
导读:看到 this question后,我的第一个想法是定义通用等价和关系运算符是微不足道的: #include cstringtemplateclass Tbool operator==(const T a,const T b) { return std::memcmp(a,b,sizeof(T)) == 0;}templateclass Tbool operator(const T a,sizeof(T)) 0;}
看到 this question后,我的第一个想法是定义通用等价和关系运算符是微不足道的:
#include <cstring>

template<class T>
bool operator==(const T& a,const T& b) {

    return std::memcmp(&a,&b,sizeof(T)) == 0;

}

template<class T>
bool operator<(const T& a,sizeof(T)) < 0;

}

使用命名空间std :: rel_ops将变得更加有用,因为它将被完全通用于运算符==和<的默认实现.显然,这不执行成员比较,而是一个按位的比较,就好像该类型只包含POD成员一样.这与C生成复制构造函数(例如,执行成员复制)的方式并不完全一致. 但是我不知道上述实现是否确实是安全的.这些结构自然地具有相同类型的包装,但是填充物的内容保证相同(例如,用零填充)?是否有任何理由或这种情况不起作用?

解决方法

Never do this unless you’re 100% sure about the memory layout,compiler behavior,and you really don’t care portability,and you really want to gain the efficiency

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读