Is there a way to use templates as static members of another class

I have the following code structure:
-----------------------------------------------------------
//myClass.h

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

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

I do understand why I get this error since legth is not initialized in the header file yet.

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

Template parameters take compile-time constants, meaning that they cannot be variables.
length is a constant though, so you'd think it should work.

Perhaps define it in the class so the compiler can see it rather than waiting for the linker:

1
2
3
4
myClass{

static const unsigned length = 5;  // give it the 5 here
static myArray<float,length> arrayX;  // now maybe this will work? 


But I'm still not convinced that will work.
Disch,
your suggestion does not work because length is a static const member which needs to be initialized outside class definition
static const integral types can be initialized in the class without any problem.

non-integral types must be initialized in the cpp file as you had originally.

But I still doubt it will solve the template problem. If it doesn't, then I don't think there's a solution that doesn't involve using a literal '5' or a macro.
static const integral types can be initialized in the class without any problem.


You mean something like below for e.g

class Test {
public:
static const int CONTANT = 10;


}

I am having problem in compilation for above syntax. Do I need a newer C++ compiler ?

Edit: Please ignore the post. I just try and it does compile in gcc version 3.4.6 20060404 (Red Hat 3.4.6-10) Seems the VC++ compiler 10 years ago I tried DID NOT COMPILE so I resort to using enum inside the class to "simulate" static const. Times have changed indeed! Good work C++ compiler writers :P
Last edited on
Topic archived. No new replies allowed.