tags:

views:

74

answers:

2

As i understood, template value need to be known in compilation time. so i write a little example just to see that i get it, but apperantly i didn't. so i get this:

`defValue' cannot appear in a constant-
 expression

can anyone please what is the problem and how it can be fixed?

#include <iostream>
template <class T,T defaultVal, int dim=255>
class Vec
{
    T _vec[dim];
    int _dim;
    public:
    Vec () : _dim(dim)
    {
       for (int i=0;i<_dim;++i)
       {
         _vec[i] = defaultVal;
       }
    }
    ~Vec () {};
// other operators and stuff
};

int main ()
{
    int defValue = 0;
    Vec < int,defValue > vecWithDefVal;// here is the problem but i don't know why
}
+1  A: 

Templates can only be parametrised by types and compile-time constants of basic types. So Vec < int,0 > vecWithDefVal; would be ok.

Oli Charlesworth
+4  A: 

C++03 14.3.2

Template non-type arguments

A template-argument for a non-type, non-template template-parameter shall be one of:

— an integral constant-expression of integral or enumeration type; or

— the name of a non-type template-parameter; or

— the address of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as & id-expression where the & is optional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or — a pointer to member expressed as described in 5.3.1 .

defValue [being a non-type argument] is neither of the above.

Change int defValue = 0; to const int defValue = 0 and your code will compile [see the first condition].

Or directly write Vec <int,0> vecWithDefVal;

Prasoon Saurav
`const int defValue = 0;` doesn't work under VC++ or GCC.
Oli Charlesworth
[It should work](http://ideone.com/G1ZpC). It works under my MSVS too :)
Prasoon Saurav
@Prasoon: Weird, I must have introduced a typo. So yes, it does work!
Oli Charlesworth