Namespaces
Variants

deduction guides for std::array

From cppreference.net
定义于头文件 <array>
template < class T, class ... U >
array ( T, U... ) - > array < T, 1 + sizeof... ( U ) > ;
(C++17 起)

std::array 提供了一个 推导指引 ,用于实现与 std::experimental::make_array 等效的功能,以便从 可变参数包 构造 std::array

( std:: is_same_v < T, U > && ... ) 不为真时,程序非良构。注意当 sizeof... ( U ) 为零时, ( std:: is_same_v < T, U > && ... ) 为真。

示例

#include <algorithm>
#include <array>
#include <cassert>
#include <type_traits>
int main()
{
    const int x = 10;
    std::array a{1, 2, 3, 5, x}; // 正确:创建 std::array<int, 5>
    assert(a.back() == x);
//  std::array b{1, 2u}; // 错误:所有参数必须具有相同类型
//  std::array<short> c{3, 2, 1}; // 错误:模板参数数量不正确
    std::array c{std::to_array<short>({3, 2, 1})}; // C++20 功能
    assert(std::ranges::equal(c, std::array{3, 2, 1}));
    static_assert(std::is_same_v<short, decltype(c)::value_type>);
}