命名空间
变体
操作

std::experimental::make_array

来自 cppreference.cn
定义于头文件 <experimental/array>
template< class D = void, class... Types >
constexpr std::array<VT /* see below */, sizeof...(Types)> make_array( Types&&... t );
(库基础 TS v2)

创建一个 std::array,其大小等于参数的数量,其元素从相应的参数初始化。 返回 std::array<VT, sizeof...(Types)>{std::forward<Types>(t)...}。

如果 Dvoid,则推导类型 VTstd::common_type_t<Types...>。 否则,它是 D

如果 Dvoidstd::decay_t<Types>... 中的任何一个是 std::reference_wrapper 的特化,则程序是非良构的。

目录

[编辑] 注释

make_array 在库基础 TS v3 中被移除,因为 std::arraystd::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 << "Returns an array of five ints? ";
    std::cout << std::boolalpha << is_array_of_5_ints << '\n';
}

输出

Returns an array of five ints? true

[编辑] 参见

to_array 从内置数组创建一个 std::array 对象
(函数模板) [编辑]