【问题标题】:std::tuple member by member comparison fails成员比较的 std::tuple 成员失败
【发布时间】:2018-03-06 11:32:37
【问题描述】:

我想测试 this very interesting answer 并提出了这个最小的实现:

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 结构有什么问题?是缺什么,还是别的?

【问题讨论】:

  • 你能更具体地谈谈“没有运气”吗?由于错误消息抱怨找不到operator==(const B&amp;, const B&amp;) 添加它似乎很明显。问题可能应该是为什么找不到它,但是您需要为此更改问题代码。

标签: c++ stdtuple


【解决方案1】:

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

由于tuple's operator== 通过 const 引用接受,它不能使用您的 const 不正确的实现。结果导致重载决议失败。

整理所有这些 const 限定符 resolves all the errors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2011-06-01
    相关资源
    最近更新 更多