简体   繁体   中英

templates value `defValue' cannot appear in a constant- expression

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
}

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM