Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias Template with non-type template parameter

Tags:

c++

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);
like image 704
embeddedstack Avatar asked May 30 '26 05:05

embeddedstack


1 Answers

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.

like image 143
463035818_is_not_a_number Avatar answered Jun 01 '26 19:06

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!