Namespaces
Variants

std::experimental:: make_array

From cppreference.net
定义于头文件 <experimental/array>
template < class D = void , class ... Types >
constexpr std:: array < VT /* see below */ , sizeof... ( Types ) > make_array ( Types && ... t ) ;
(库基础技术规范 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 已在 Library Fundamentals 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>...>,
                      "当 D 为 void 时,Types 不能包含 reference_wrapper");
    };
    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 << "Returns an array of five ints? ";
    std::cout << std::boolalpha << is_array_of_5_ints << '\n';
}

输出:

Returns an array of five ints? true

参见

C++ 文档 关于 std::array 推导指南
从内置数组创建 std::array 对象
(函数模板)