当用作非类型模板参数时,是否可以自动派生 std::array 的大小

Can the size of an std::array be automatically derived when used as a non-type template parameter

本文关键字:派生 std array 是否 类型 参数      更新时间:2023-10-16

以下作品。但是,是否可以省略 SIZE 模板参数(即不一定是数组的 SIZE 模板参数(?

template <
class T,
size_t SIZE,
std::array<T, SIZE> & ARR
>
class Foo{};

换句话说,编译器是否可以从数组模板参数中推断出 SIZE?从而消除界限

const size_t SIZE,

使用 C++17 您可以使用自动模板参数:

template<auto&>
struct Foo {};

然后,您可以发送对全局的引用:

void test() {
static auto arr = std::array{1, 2, 3, 4, 5}; // no linkage works in C++17
Foo<arr> f{};
}

您可以在编译时通过std::tuple_size(std::array)获取大小(自 C++11 起(,例如

template <
class ARRAY
>
struct Foo{
static constexpr size_t SIZE = std::tuple_size<ARRAY>::value;
using T = typename ARRAY::value_type;
};

并将其用作

Foo<array<int, 3>> f;