what does T = 0 mean in a template parameter?

Oct 28, 2024 at 7:38pm
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;
}
Oct 28, 2024 at 10:56pm
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 Oct 28, 2024 at 10:58pm
Oct 29, 2024 at 9:19am
@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 Oct 29, 2024 at 9:19am
Oct 29, 2024 at 1:15pm
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 Oct 29, 2024 at 1:16pm
Oct 31, 2024 at 11:08am
Indeed:

"initialized with value 0" limit what type the T can be?
Topic archived. No new replies allowed.