2

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?

bitmask
  • 32,434
  • 14
  • 99
  • 159
Vindhya G
  • 1,339
  • 2
  • 21
  • 46
  • 1
    A link to the website would be helpful. – Mark Ransom Aug 04 '12 at 05:13
  • Its just an mcq where there were 3 options out of which these were first two,third one was a template declaration involving typename and had to pick up invalid one and the answer is one with double.. – Vindhya G Aug 04 '12 at 05:15
  • 5
    I think it basically comes down to it being difficult to specify what floating point equality means in a way that can work reasonably well across different compilers and floating point representations. – Vaughn Cato Aug 04 '12 at 05:19
  • http://stackoverflow.com/questions/2183087/c-why-cant-i-use-float-value-as-a-template-parameter – Vaughn Cato Aug 04 '12 at 05:21
  • BTW: If you are looking for a way around this restriction. Create a class that has an inline static method that returns the value you want, and pass the class as the template parameter instead. – Vaughn Cato Aug 04 '12 at 05:34
  • Your question is [answered](http://stackoverflow.com/a/11518757/241631) in the question linked by @VaughnCato. – Praetorian Aug 04 '12 at 05:35

1 Answers1

3

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.

vidit
  • 6,293
  • 3
  • 32
  • 50