Question

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?

Was it helpful?

Solution

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 ...

Floating-point numbers and class-type objects are not allowed as nontype template parameters.

template <double VAT>       // ERROR: floating-point values are not
double process(double v) { // allowed as template parameters
    return v * VAT;
}

template <std::string name> // ERROR: class-type objects are not
class MyClass {             // allowed as template parameters
  /* ... */
};

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

template <double VAT> double process(double v);

is initialized with two different double values as

template <(double) 2/3> double process(2.3)

template <(double) 1/3> double process(2.4);

they might not have same bit representation because of double nontype, which confuses the compiler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top