3

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

I have this class:

template<typename ValueType, ValueType DefaultValue>
class SomeClass
{
    public:
        SomeClass() : m_value(DefaultValue){}

        ValueType m_value;
};

I want to use it like this:

SomeClass<int, 1> intObj; //ok
SomeClass<float, 1.f> floatObj; //error: 'float' : illegal type for non-type template parameter 'DefaultValue'

Can you please explain me why I get this error when using float?

I want to use something similar to represent RGBA colors and to initialize the channels with default value for different color representations(White for example).

Community
  • 1
  • 1
Mircea Ispas
  • 19,462
  • 29
  • 118
  • 205

5 Answers5

3

The language does not allow the use of floating-point types as non-type template arguments. For an extensive discussion, see Why can't I use float value as a template parameter?

Community
  • 1
  • 1
NPE
  • 464,258
  • 100
  • 912
  • 987
3

§ 14.1/7 (C++11 N3485) explicitly forbids this:

A non-type template-parameter shall not be declared to have floating point, class, or void type. [ Example:

template<double d> class X; // error  
template<double* pd> class Y; // OK  
template<double& rd> class Z; // OK
chris
  • 58,138
  • 13
  • 137
  • 194
0

C++ doesn't support floating-point non-type template parameters unfortunately.

Stuart Golodetz
  • 19,702
  • 4
  • 49
  • 80
0

You get that error because non-type template parameters cannot be of type float. They may only be integrals, enumerations, member-pointers or addresses.

K-ballo
  • 78,684
  • 20
  • 152
  • 166
0

That's simple: nontype template parameters have to be compiletime constants of integral type or pointer type, i.e. bool, enums, pointers, pointer-to-members, long, int, short, char. Floating point parameters are not allowed in the current standard.

Arne Mertz
  • 23,487
  • 2
  • 45
  • 88