tags:

views:

65

answers:

3

I have the following code structure:

myClass.h

class myClass
{
public:
    void DoSomething(void);
};

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?

+3  A: 

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

GMan
This is legal (and probably preferable) since the `static const` and the fact that it is an integral type qualify it as a compile-time constant.
Tim Yates
+1  A: 

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.

sbi
A: 

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).

Tomek