我想测试这个非常有趣的答案,并提出了这个最小的实现:
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; }
};
Run Code Online (Sandbox Code Playgroud)
一个简单的测试:
int main() {
A x(42);
A y(x);
std::cout << (x==y) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
一切都很好,直到我定义一个简单的struct B {};并尝试添加它的一个实例作为成员.我一写
std::tuple<int, B> members;
Run Code Online (Sandbox Code Playgroud)
这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))
^
Run Code Online (Sandbox Code Playgroud)
我想提供operator==给B:
struct B
{
bool operator==(const B &){ return true; }
};
Run Code Online (Sandbox Code Playgroud)
并从编译器中获得额外的:
candidate: bool B::operator==(const B&) <near match>
bool operator==(const B &){ return true; }
^
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释B结构有什么问题吗?是缺少什么,否则?
这最终是正确的.你没有const限定B(或者A说是那个)比较运算符及其参数.
由于元组operator==接受const引用,它不能使用const不正确的实现.因此,重载决策失败.
整理所有这些const限定符可以解决所有错误.