获取 c 数组上的 begin 返回类型

Get the return type of begin on a c array

本文关键字:begin 返回类型 数组 获取      更新时间:2023-10-16

我想以通用方式获取std::begin的返回类型。我目前的解决方案是:

using type = decltype(std::begin(std::declval<T>()));

它在T = std::vector<int>时有效.但我不明白为什么以下内容不起作用:

using type = decltype(std::begin(std::declval<int[3]>()));

我收到错误:

example.cpp:83:60: error: no matching function for call to ‘begin(int [3])’
     using type = decltype(std::begin(std::declval<int[3]>()));

如何以通用方式获取std::begin的返回类型?

数组

的重载为:

template< class T, std::size_t N > 
constexpr T* begin( T (&array)[N] );

std::declval<int[3]>()给你一个int(&&)[3],这与那个重载不匹配。它也与正常的容器过载不匹配,因为这些是SFINAE-ed c.begin()。因此,您没有匹配的功能。

相反,您需要的是将数组的左值引用传递给begin(),以使迭代器返回。因此,在使用别名时,您需要手动提供该 lvalue 引用:

template <class T>
using type = decltype(std::begin(std::declval<T>()));
using arr = type<int(&)[3]>; // int*

或者让别名本身为您提供左值引用:

template <class T>
using type = decltype(std::begin(std::declval<T&>()));
using arr = type<int[3]>; // int*

前者对我来说似乎更正确,但是 YMMV。