[英]std::tuple member by member comparison fails
I wanted to test this very interesting answer and came out with this minimal implementation: 我想测试这个非常有趣的答案,并给出了最小的实现:
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; }
};
and a simple test: 和一个简单的测试:
int main() {
A x(42);
A y(x);
std::cout << (x==y) << std::endl;
return 0;
}
Everything's fine, until I define a simple struct B {};
一切都很好,直到我定义了一个简单的
struct B {};
and try to add an instance of it as a member. 并尝试将其实例添加为成员。 As soon as I write
我一写
std::tuple<int, B> members;
the operator==
isn't ok anymore and I get this message from the compiler (gcc 5.4.1): 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))
^
I tried providing an operator==
to B
: 我尝试为
B
提供一个operator==
:
struct B
{
bool operator==(const B &){ return true; }
};
and had an extra from compiler: 并从编译器中获得了额外收益:
candidate: bool B::operator==(const B&) <near match>
bool operator==(const B &){ return true; }
^
Can anyone explain what's wrong with B struct? 谁能解释B结构有什么问题? Is it lacking something, or else?
是否缺少某些东西?
It's ultimately const correctness. 最终是const正确性。 You didn't const qualify
B
's (or A
's, for that matter) comparison operator and its parameter consistently. 您没有使
B
(或A
)比较运算符及其参数一致地常量。
Since tuple's operator==
accepts by a const reference, it cannot use your const-incorrect implementation. 由于元组的
operator==
被const引用接受,因此它不能使用const不正确的实现。 And overload resolution fails as a consequence. 结果,过载解析失败。
Tidying up all of those const qualifiers resolves all the errors . 整理所有这些const限定符可以解决所有错误 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.