对于给定的类,如果我想编写所有的比较运算符,为了避免代码重复,我会写这样的东西:
class B {
public:
bool operator==(Type const& rhs) const {
return as_tuple() == rhs.as_tuple();
}
bool operator!=(Type const& rhs) const {
return as_tuple() != rhs.as_tuple();
}
// .. and same for other operators ..
private:
auto as_tuple() const {
return std::tie(a, b, c); // all the members
}
};
Run Code Online (Sandbox Code Playgroud)
我可以as_tuple()在那里实现,std::tie()或者我可以实现它std::forward_as_tuple().有区别吗?我应该选择哪个?
我们来看一下签名吧.std::tie()是:
Run Code Online (Sandbox Code Playgroud)template< class... Types > constexpr tuple<Types&...> tie( Types&... args ) noexcept;
Run Code Online (Sandbox Code Playgroud)template< class... Types > constexpr tuple<Types&&...> forward_as_tuple( Types&&... args ) noexcept;
唯一的区别是前者只接受左值,而后者接受左值和左值.如果你的所有输入都是左值,就像它们在你的用例中一样,它们完全等价.
std::tie()主要是作为赋值的左侧(例如std::tie(a, b) = foo;,解包a pair),而std::forward_as_tuple()主要是为了在函数中传递东西以避免复制.但它们都可以用来解决这个问题.tie显然是相当短,可以说是更为人所知(tie使用它实现的cppreference示例operator<),所以这将得到我的投票.