简体   繁体   中英

Templates and const on c++

I have the following template:

#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; 
}

But the program will not compile because a template value must be known during compilation time, meaning const or const-literal.

I really dont understad this error, can anyone explain it to me?

Template class is created at compile time , so the value has to be known at compile time. If it is not const it is not known until run-time, so the compiler can't create the template class.

As the compiler told you, it must be a constant expression.

Use const int defValue = 0;

Generally, using a different type for each value you want to use isn't that useful. In most cases I would expect that you want to use T() as the default default value (no, the duplicate "default" isn't a type) with the possibility of overriding an object's default value using a constructor parameter. Using a template argument for the default doesn't work when you want to determine the value at run-time.

In fact the code in the question shows why using the default value as a template argument is problematic: you can only use constant expressions as arguments. That is, only arguments the compiler can figure out at compile time are viable. Moreover, these need to be clearly labeled as being constant as well:

int const defValue = 0;

To deal with non-integer types you could consider using a pointer or a reference to an object in namespace scope. However, I would think that using a constructor parameter is what is really needed here.

const int defValue = 0;
Vec<int, defValue> 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