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
  • 20,260
  • 32
  • 123
  • 211

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
  • 486,780
  • 108
  • 951
  • 1,012
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
  • 60,560
  • 13
  • 143
  • 205
0

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

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 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
  • 80,396
  • 20
  • 159
  • 169
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
  • 24,171
  • 3
  • 51
  • 90