what does T = 0 mean in a template parameter?

What does T = 0 mean in the following code:


1
2
3
4
template<typename T, T = 0>
T moduloOf(T a, T b) {
    return a % b;
}
It makes a non-type template parameter of type T with a default value of 0.

C++17 introduced this alternative syntax:
1
2
3
4
template <auto T = 0>
T moduloOf(T a, T b) {
    return a % b;
}
Last edited on
@mbozzi T is a type in the original code. In your code T isn't a type, but it's being used as a type, so the code doesn't compile.
Last edited on
1
2
3
4
template<typename T, T = 0>
T moduloOf(T a, T b) {
    return a % b;
}

The template takes one typename argument and one non-type argument.
1
2
auto answer1 = moduloOf<int>( 7, 3 );    // non-type has value 0
auto answer2 = moduloOf<int,42>( 7, 3 ); // non-type has value 42 

The non-type template parameter is unnamed and is not used anywhere in the templated function.


Does the "initialized with value 0" limit what type the T can be?
Similar to concepts in modern C++?
Last edited on
Registered users can post here. Sign in or register to post.