std::tie 和 std::forward_as_tuple 有什么区别
What is the difference between std::tie and std::forward_as_tuple
对于给定的类,如果我想编写所有比较运算符,以避免代码重复,我会写这样的东西:
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<
(,所以这将得到我的投票。
这是一篇关于同一主题的好文章。
从链接中的文章:
总之,当您需要构建元组时,请使用:
std::make_tuple
如果需要返回元组中的值,std::tie
如果需要返回元组中的左值引用,std::forward_as_tuple
是否需要保留输入的引用类型以构建元组。
相关文章:
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- "using namespace std;"在C++的作用是什么?
- 传递给std::function template的template参数究竟代表什么
- "std::unique_XXX"命名约定背后的基本原理是什么?
- 什么是 std::exception::what() 以及为什么要使用它?
- C++如果必须在编译时确定大小,std::array 有什么意义?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- 什么是自动 t1=std::make_tuple(case1==case2,整数)的值
- C++std::atomic在程序员级别保证了什么
- 当为可变性配置时,boost::heap::d_ary_heap 保留的额外 std::list 的目的是什么?
- 引用 std::any 或 not_yet_in_std::whatever 的惯用方式是什么?
- 在什么条件下使用 std::memcpy 在对象之间复制是安全的?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 在 C# 中等效的 std::rotate() 是什么?
- 什么是 std::function::argument_type 的替代品?
- 什么是 std::jthread 在 c++20 中?
- std::enable_if 和 std::enable_if_t 有什么区别?
- "owned pointer"和 std::shared_ptr 的"stored pointer"有什么区别?