开发者

C++, non parameter types for templates: only const variables?

I dont understand why a template parameter can be initialized only with a const variable. As in, why doesn't the following code work:

#include <iostream>
template <class T,int dim>
class Vec
{
    T _vec[dim];
    开发者_开发技巧int _dim;
    public:
    Vec () : _dim(dim) {};
    ~Vec () {};
    // other operators and stuff
};
int main () {
   int dim = 3;
   Vec < int, dim> vecInt3;
}

If I add a const to the definition of dim in the main, everything is fine. Why is that?


Integer types parameters must be compile-time constants. You have to either use an integer literal or make your variable const. The reason is the template is instantiated before runtime and if there's a chance you can later change a variable name the program will behave inconsistent with the template.


I think, that's becouse you can't create a table with a variable as a length in T _vec[dim]. Why not think of a built-in vector type instead?


First, template are built at compile time, that is why you must use a const value: it can't be calculated at runtime. Infact when you compile your code the class will be compiled one time for each different use of it's parameters.

After this, the code should work if there aren't other syntax errors.

An important note before you go mad: you can't split templates in header/cpp file, you must write header and implementation on the same file!


Because the template parameter should be calculated at compile time. Compiler will make codes for different parameters.

In your case, you can see that if dim isn't a const, compiler would not know how much spaces should alloc for vecInt3. In factVec<int, 1> and Vec<int, 2> is different type.

If you want a vector with dynamic size, you could see std::vector to get some idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜