std::experimental::make_array
来自cppreference.com
< cpp | experimental
<tbody>
</tbody>
| 在标头 <experimental/array> 定义
|
||
template< class D = void, class... Types > constexpr std::array<VT /* 见下文 */, sizeof...(Types)> make_array( Types&&... t ); |
(库基础 TS v2) | |
创建一个 std::array,其大小等于实参数量,且其各元素从对应实参初始化。返回 std::array<VT, sizeof...(Types)>{std::forward<Types>(t)...}。
若 D 为 void,则推出的类型 VT 为 std::common_type_t<Types...>。否则,类型为 D。
若 D 为 void,且 std::decay_t<Types>... 中任意一者是 std::reference_wrapper 的特化,则程序非良构。
注解
make_array 在库基础 TS v3 中被移除,因为 std::array 的推导指引与 std::to_array 已在 C++20 中。
可能的实现
namespace details
{
template<class> struct is_ref_wrapper : std::false_type{};
template<class T> struct is_ref_wrapper<std::reference_wrapper<T>> : std::true_type{};
template<class T>
using not_ref_wrapper = std::negation<is_ref_wrapper<std::decay_t<T>>>;
template<class D, class...> struct return_type_helper { using type = D; };
template<class... Types>
struct return_type_helper<void, Types...> : std::common_type<Types...>
{
static_assert(std::conjunction_v<not_ref_wrapper<Types>...>,
"Types cannot contain reference_wrappers when D is void");
};
template<class D, class... Types>
using return_type = std::array<typename return_type_helper<D, Types...>::type,
sizeof...(Types)>;
}
template<class D = void, class... Types>
constexpr details::return_type<D, Types...> make_array(Types&&... t)
{
return {std::forward<Types>(t)...};
}
|
示例
运行此代码
#include <experimental/array>
#include <iostream>
#include <type_traits>
int main()
{
auto arr = std::experimental::make_array(1, 2, 3, 4, 5);
bool is_array_of_5_ints = std::is_same<decltype(arr), std::array<int, 5>>::value;
std::cout << "返回五个 ints 的数组?";
std::cout << std::boolalpha << is_array_of_5_ints << '\n';
}
输出:
返回五个 ints 的数组?true
参阅
| 从内建数组创建 std::array 对象 (函数模板) |