iFr*_*cht 7 c++ comparison operator-overloading c++11
有n个不同的类,它们都应该与之相当,operator==
并且operator!=
有必要手动实现(n ^ 2 - n)*2个运算符.(至少我认为这是一个术语)
三个班级将是12个,四个班级为24个.我知道我可以用其他运算符来实现很多这样的运算符:
operator==(A,B); //implemented elsewhere
operator==(B,A){ return A == B; }
operator!=(A,B){ return !(A == B); }
Run Code Online (Sandbox Code Playgroud)
但它似乎仍然很乏味,特别是因为它A == B
总会产生相同的结果,B == A
并且似乎没有任何理由来实现它们的两个版本.
有没有解决的办法?难道我真的要落实A == B
和B == A
手动?
使用Boost.Operators,然后你只需要实现一个,boost将为你定义其余的样板.
struct A
{};
struct B : private boost::equality_comparable<B, A>
{
};
bool operator==(B const&, A const&) {return true;}
Run Code Online (Sandbox Code Playgroud)
这允许以任何顺序比较等式/不等式的实例A
和B
进行比较.
注意: private
由于Barton-Nackman技巧,继承在这里起作用.
归档时间: |
|
查看次数: |
645 次 |
最近记录: |