繁体   English   中英

std :: tuple成员逐成员比较失败

[英]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))
                                 ^

我尝试为B提供一个operator==

struct B
{
    bool operator==(const B &){ return true; }
};

并从编译器中获得了额外收益:

candidate: bool B::operator==(const B&) <near match>
     bool operator==(const B &){ return true; }
          ^

谁能解释B结构有什么问题? 是否缺少某些东西?

最终是const正确性。 您没有使B (或A )比较运算符及其参数一致地常量。

由于元组的operator==被const引用接受,因此它不能使用const不正确的实现。 结果,过载解析失败。

整理所有这些const限定符可以解决所有错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM