对于一个给定的类,如果我想写所有的比较运算符,为了避免代码重复,我会这样写:
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
}
};
我可以用 std::tie()
实现 as_tuple()
或者我可以用 std::forward_as_tuple()
实现它.有区别吗?我应该选择哪个?
最佳答案
让我们看看签名。 std::tie()
是:
template< class... Types > constexpr tuple<Types&...> tie( Types&... args ) noexcept;
鉴于 std::forward_as_tuple()
是:
template< class... Types > constexpr tuple<Types&&...> forward_as_tuple( Types&&... args ) noexcept;
唯一的区别是前者只接受左值,而后者接受左值和右值。如果您的所有输入都是左值,就像它们在您的用例中一样,那么它们是完全等价的。
std::tie()
主要用作赋值的左侧(例如 std::tie(a, b) = foo;
解压 pair
),而 std::forward_as_tuple()
主要是为了在函数中传递东西以避免复制。但是它们都可以用来解决这个问题。 tie
显然要短一些,而且可以说更广为人知(tie
的 cppreference 示例使用它来实现 operator<
),所以我会投票。
关于c++ - std::tie 和 std::forward_as_tuple 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51971003/