未命名的非类型模板参数有什么意义?

and*_*eee 5 c++ templates generic-programming non-type

根据参考,非类型模板参数的名称是可选的,即使在分配默认值时也是如此(参见(1)和(2))。因此这些模板结构是有效的:

template <int> struct Foo {};
template <unsigned long = 42> struct Bar {};
Run Code Online (Sandbox Code Playgroud)

我还没有看到访问非类型参数值的可能性。我的问题是:未命名/匿名非类型模板参数有什么意义?为什么名称是可选的?

Jar*_*d42 8

首先,我们可以将声明与定义分开。所以声明中的名称并没有真正的帮助。和名称可能用于定义

template <int> struct Foo;
template <unsigned long = 42> struct Bar;

template <int N> struct Foo {/*..*/};
template <unsigned long N> struct Bar {/*..*/};
Run Code Online (Sandbox Code Playgroud)

专业化是定义的特例。

然后 name 可以不用,所以我们可以省略它:

template <std::size_t, typename T>
using always_t = T;

template <std::size_t ... Is, typename T>
struct MyArray<std::index_sequence<Is...>, T>
{
    MyArray(always_t<Is, const T&>... v) : /*..*/
};
Run Code Online (Sandbox Code Playgroud)

或用于 SFINAE

template <typename T, std::size_t = T::size()>
struct some_sized_type;
Run Code Online (Sandbox Code Playgroud)


眠りネ*_*ネロク 5

什么是点无名/匿名的非类型模板参数?

我能想到的专业:

template<int = 42>
struct Foo{
   char x;
};

template<>
struct Foo<0> {
   int x;
};

template<>
struct Foo<1> {
   long x;
};
Run Code Online (Sandbox Code Playgroud)

然后:

Foo<0> a; // x data member is int
Foo<1> b; // x data member is long
Foo<7> c; // x data member is char
Foo<>  d; // x data member is char
Run Code Online (Sandbox Code Playgroud)