开发者

How to use static members as template arguments?

I have the following code structure:

myClass.h

class myClass
{
public:
    void DoSomething(v开发者_如何学Gooid);
};

myClass.cpp

#include myClass.h

static const unsigned length = 5;
static myArray<float, length> arrayX;

void myClass::DoSomething(void)
{
    // does something using length and array X
}

Now I want to convert the static variable defined at the file scope to be static members of the class. I do the following;

myClass.h

class myClass
{
    static const unsigned length;
    static myArray<float,length> arrayX;

public:
    void DoSomething(void);
};

myClass.cpp

#include myClass.h

const unsigned myClass::length = 5;
myArray<float, length> myClass::arrayX;

void myClass::DoSomething(void)
{
    // does something using length and array X
}

However, I get an error:

C2975: 'Length' : invalid template argument for 'myArray', expected compile-time constant expression myClass.h

I do understand I get this error because length is not initialized in the header file yet. How can I get around this?


It needs to be a constant expression, so the best you can do is move = 5 to the header.


However, I was wondering if there is a way to get around this.

Look at your code again. That myArray<float,length> is declared as a class data member in the header.
In order for the compiler to know what myClass is, it must know the full definition of that data member. But the full definition of myArray<float,length> in turn requires length to be known, because without its template arguments, myArray is not a type, but a template, and data members must be types, not class templates.

From this it's clear that, in order to have a myArray instance as a class member, the length must be known when the class is compiled, myArray is to be a member of.


Have you tried:

myArray<float, myClass::length> myClass::arrayX;
               ^^^^^^^^^^

You may also need to change header:

class myClass
{
    static const unsigned length = 5;

and change definition of myClass::length in .cpp to not contain "= 5" (or remove it completly).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜