简体   繁体   English

具有非类型模板参数的别名模板

[英]Alias Template with non-type template parameter

My expectation was that this code cannot be compiled, but it can.我的期望是这段代码不能被编译,但它可以。 How can this code work?这段代码如何工作? Even integer is not a template.甚至 integer 也不是模板。

template <int>
using A = int;

void f(A<4> foo = 0);

Doesn't it come this way?不是这样过来的吗?

void f(int<4> foo = 0);

Doesn't it come this way?不是这样过来的吗?

No.不。

A is an alias template. A是别名模板。 It has an unnamed unused int parameter.它有一个未命名的未使用的int参数。 No matter what argument is used A is always an alias for int .无论使用什么参数, A始终是int的别名。 Thats what using A = int;这就是using A = int; means.方法。

The function declaration is basically just function 申报基本上就是

void f(int foo = 0);

Perhaps you are not familiar with unnamed unused template parameter.也许您不熟悉未命名的未使用模板参数。 The alias can be equivalently written as:别名可以等效地写为:

template <int Value>
using A = int;

As Value is not used its name can be ommitted.由于未使用Value ,因此可以省略其名称。


Perhaps you are confused by int appearing twice in the alias template.也许您对在别名模板中出现两次的int感到困惑。 The first int is the (unnamed unused) parameter, the second int is the aliased type, the two are unrelated.第一个int是(未命名未使用的)参数,第二个int是别名类型,两者无关。

You can write similar alias with a int parameter to alias double :您可以使用int参数将类似的别名写入 alias double

template <int>
using B = double;

Here any B<n> is an alias for double .这里任何B<n>都是double的别名。

Or you can write similar alias with a type parameter to alias int :或者您可以将带有类型参数的类似别名写入别名int

template <typename>
using C = int;

Here any C<T> , eg C<std::string> or C<foo> is an alias for int .这里任何C<T> ,例如C<std::string>C<foo>都是int的别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM