标准::元组成员逐个成员比较失败

std::tuple member by member comparison fails

本文关键字:成员 比较 失败 元组 组成员 标准      更新时间:2023-10-16

我想测试这个非常有趣的答案,并提出了这个最小的实现:

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==接受常量引用,因此它不能使用您的常量不正确的实现。因此,过载解决失败。

整理所有这些常量限定符可以解决所有错误。