Reputation: 21
I have the following code structure:
class myClass
{
public:
void DoSomething(void);
};
#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;
class myClass
{
static const unsigned length;
static myArray<float,length> arrayX;
public:
void DoSomething(void);
};
#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?
Upvotes: 1
Views: 1700
Reputation: 4659
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).
Upvotes: 0
Reputation: 224189
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.
Upvotes: 1
Reputation: 504313
It needs to be a constant expression, so the best you can do is move = 5
to the header.
Upvotes: 4