std::tie 和 std::forward_as_tuple 有什么区别

What is the difference between std::tie and std::forward_as_tuple

本文关键字:std 什么 区别 tuple as forward tie      更新时间:2023-10-16

对于给定的类,如果我想编写所有比较运算符,以避免代码重复,我会写这样的东西:

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的cpp首选项示例使用它来实现operator<(,所以这将得到我的投票。

这是一篇关于同一主题的好文章。

从链接中的文章:

总之,当您需要构建元组时,请使用:

  1. std::make_tuple如果需要返回元组中的值,
  2. std::tie如果需要返回元组中的左值引用,
  3. std::forward_as_tuple是否需要保留输入的引用类型以构建元组。