Home > Software engineering >  Alias Template with non-type template parameter
Alias Template with non-type template parameter

Time:01-25

My expectation was that this code cannot be compiled, but it can. How can this code work ? Even integer is not a template.

template <int>
using A = int;

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

Doesn't it come this way?

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

CodePudding user response:

Doesn't it come this way?

No.

A is an alias template. It has an unnamed unused int parameter. No matter what argument is used A is always an alias for int. Thats what using A = int; means.

The function declaration is basically just

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.


Perhaps you are confused by int appearing twice in the alias template. The first int is the (unnamed unused) parameter, the second int is the aliased type, the two are unrelated.

You can write similar alias with a int parameter to alias double:

template <int>
using B = double;

Here any B<n> is an alias for double.

Or you can write similar alias with a type parameter to alias int:

template <typename>
using C = int;

Here any C<T>, eg C<std::string> or C<foo> is an alias for int.

  •  Tags:  
  • c
  • Related