名稱空間
變體
操作

std::experimental::make_array

來自 cppreference.com
< cpp‎ | 實驗性
定義於標頭檔案 <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)...}。

如果 Dvoid,則推導型別 VTstd::common_type_t<Types...>。否則,它是 D

如果 Dvoid 且任何 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>...>,
                      "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

[編輯] 另見

C++ 文件 for std::array 推導指南
從內建陣列建立一個 std::array 物件
(函式模板) [編輯]