标准::元组成员逐个成员比较失败
std::tuple member by member comparison fails
我想测试这个非常有趣的答案,并提出了这个最小的实现:
class A
{
enum M { a };
std::tuple<int> members;
public:
A() { std::get<M::a>(members) = 0; }
A(int value) { std::get<M::a>(members) = value; }
A(const A & other) { members = other.members; }
int get() const { return std::get<M::a>(members); }
bool operator==(A & other) { return members == other.members; }
};
和一个简单的测试:
int main() {
A x(42);
A y(x);
std::cout << (x==y) << std::endl;
return 0;
}
一切都很好,直到我定义一个简单的struct B {};
并尝试将其实例添加为成员。只要我写
std::tuple<int, B> members;
operator==
不再正常,我从编译器(gcc 5.4.1)收到以下消息:
error: no match for ‘operator==’ (operand types are ‘std::__tuple_element_t<1ul, std::tuple<int, B> > {aka const B}’ and ‘std::__tuple_element_t<1ul, std::tuple<int, B> > {aka const B}’)
return bool(std::get<__i>(__t) == std::get<__i>(__u))
^
我尝试提供operator==
B
:
struct B
{
bool operator==(const B &){ return true; }
};
并且有一个额外的编译器:
candidate: bool B::operator==(const B&) <near match>
bool operator==(const B &){ return true; }
^
谁能解释一下 B 结构有什么问题?是缺少什么,还是缺少什么?
这最终是正确的。您没有一致地限定B
的(或A
的)比较运算符及其参数。
由于元组的operator==
接受常量引用,因此它不能使用您的常量不正确的实现。因此,过载解决失败。
整理所有这些常量限定符可以解决所有错误。
相关文章:
- 三向比较运算符成员与非成员实现
- 用于基于成员字段或函数创建比较器的快捷方式
- 如何通过比较彼此的成员从QStringList中删除元素
- 在单元测试中,如何在不使用 operator== 的情况下比较两个对象,这可能会错过新成员?
- 重载对象成员的比较运算符
- 如何使用自定义比较器初始化类数据成员,该成员是 std::set
- 将比较器传递给Priority_queue,称为班级成员
- 具有多个空成员的 std::元组上的比较无法在 GCC 上编译
- 标准::元组成员逐个成员比较失败
- 通过构造函数与直接初始化进行成员初始化的比较
- 为什么比较和交换操作同时存在免费函数和成员函数?
- 没有成员作为唯一标识符的两个类实例的比较
- 将对象成员数组与字符串进行比较
- 比较存储在向量中的类对象的私有成员变量 - C++
- 将非静态数据成员与常量成员进行比较
- std::具有自定义比较函数结果的排序函数错误:必须调用对非静态成员函数的引用
- C++使用成员字段设置比较器
- 如何比较 2 个对象的私有成员?
- 使用结构的成员变量比较 next_permutation()
- C++一个自定义的成员比较函数