【发布时间】: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&, const B&)添加它似乎很明显。问题可能应该是为什么找不到它,但是您需要为此更改问题代码。