In the example code, compiled in C 17:
template <typename T = int>
struct A
{
static constexpr double b = 0.5;
};
int main()
{
A a; // compiles
double c = A<>::b; // compiles
double d = A::b; // fails to compile
// ...
return 0;
}
A::b
fails to compile because:
main.cpp:13:16: error: 'template<class T> struct A' used without template arguments
13 | double d = A::b; // fails to compile
I thought in C 17 automatic template type deduction would take care of this since I have the default template argument. What am I missing?
CodePudding user response:
Each instantiated class instance has own A<T>::b
member.
#include <iostream>
template <typename T = int>
struct A
{
static constexpr double b = 0.5;
};
int main()
{
std::cout << &A<int>::b << "\n";
std::cout << &A<char>::b << "\n";
return 0;
}
Compiled with clang 13 with the option -std=c 17
. Output:
0x402008
0x402018
Think about if A::b
could be compiled, which address would be selected by the compiler.
The live example https://godbolt.org/z/GqhjMvoz6
As for failed to compile double d = A::b;
with the default template parameter, this is the rule, templates must be instantiated used with using angle brackets <, >
.