2

Possible Duplicate:
C++: Why can't I use float value as a template parameter?

I can define a template class:

template <int A> C {};

But I can't define a class like:

template <float A> C{};

I think in the expression:

const float a = 10.0f;

a is a const experision, and I can use it to instantiate a float none-type template parameter

C<a> c();

but unfortunately, it's illegal. Why?

Community
  • 1
  • 1
user1400047
  • 247
  • 2
  • 10
  • 1
    Float numbers are not known at compile time even you declare it const. Say, you have two const a and b, unlike integers, it's not possible to know a+b at compile time because possible rounding error which could be configured at runtime. In fact the value 0.1 cannot be accurately represented by binary floating point and thus such a constant will not be known until runtime – Yan Zhou Jul 17 '12 at 08:24
  • Take a look at this answer: http://stackoverflow.com/a/2185852/484230. In summary even two floats that are logically identical might not result in the same bit pattern, thus you would generate different templates for them, which goes against the rationale behind templates – Martin Jul 17 '12 at 08:27

1 Answers1

2

A possible motivation for this not being allowed by the standard is that identical template parameters can appear different when treated as floats as not all floats are precisely representable. For example, would

C<1.0f/3.0f> c;

and

C<2.0f/6.0f> c;

be of the same type?

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Yes, because they're both `C<0>` :-) – Kerrek SB Jul 17 '12 at 08:21
  • 1
    yes (at least for IEE754 floats), because all literal values are exactly representable as floats and the exact result should be rounded in the same way to fit float representation. However, C<0.1f/0.3f> may be another type :) – user396672 Jul 17 '12 at 09:02