I read on a website that the declaration
template <int x>
int func() {
return x;
}
is valid while the following is not
template <double x>
double func() {
return x;
}
Why is the first a legal declaration for a template function while the second is not?
It is not valid because it is not an integral type. There are certain restrictions on nontype template parameters and this is one of them, which says ...
The above is quoted from C++ Templates. I take no credits for it.
The reason why they are not valid for template initialization, as per my understanding, is because types like float and double don't have a defined implementation in C++. So when a template like
is initialized with two different double values as
they might not have same bit representation because of double nontype, which confuses the compiler.