std::tuple::get return const Type&&

std::tuple::get returning const Type&&

本文关键字:Type const get tuple std return      更新时间:2023-10-16

我刚刚阅读了 C++17 的更新界面,用于 cpp首选项 http://en.cppreference.com/w/cpp/utility/tuple/get std::tuple::get,新的重载从get<>()函数返回const Type&&。 为什么要返回const Type&&而不是普通const Type&? 不能从任一类型的实例中移动。

作为参考,这些是我所指的函数声明

template< class T, class... Types >
constexpr const T&& get(const tuple<Types...>&& t);

template< std::size_t I, class... Types >
constexpr std::tuple_element_t<I, tuple<Types...> >const&&
get( const tuple<Types...>&& t );

谷歌搜索出现了问题 2485,它指出了这样的缺陷:

#include <functional>
#include <string>
#include <tuple>
using namespace std; 
string str1() { return "one"; }
const string str2() { return "two"; }
tuple<string> tup3() { return make_tuple("three"); }
const tuple<string> tup4() { return make_tuple("four"); }
int main() {
  // cref(str1()); // BAD, properly rejected
  // cref(str2()); // BAD, properly rejected
  // cref(get<0>(tup3())); // BAD, properly rejected
  cref(get<0>(tup4())); // BAD, but improperly accepted!
}

在这种特殊情况下,cref 删除了 const T&& 重载,但通过 get 传递它掩盖了元组及其成员是临时的。

您可以从const&&的可变数据中移动。 它相对晦涩难懂。

相关文章: