std::experimental::make_array

来自cppreference.com
定义于头文件 <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

Dvoid ,且 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::experimental::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::experimental::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

参阅

从内建数组创建 std::array 对象
(函数模板)