Samaursa
Samaursa

Reputation: 17271

Defining static const variables of a template class

I have a vector class which has some static const variables like ZERO. Now since vector is often implemented as a template class (and mine is no exception), I see a lot of this code:

template<> const Vector2<float> Vector2<float>::ZERO;
template<> const Vector2<float> Vector2<float>::UNIT_X(1, 0);
//... and so on, and then all code duplicated for other types (int, double, long double)
// including different sizes of the Vector (Vector2, Vector3, Vector4)

My question is, can I do something like this instead to avoid duplicating code just for a different type:

template <typename T, unsigned int SIZE>
const Vector<T, SIZE> Vector<T, SIZE>::ZERO;

Can that satisfy all future types? If not, will it make a difference if I put the following to explicitly define the classes for the various types:

template Vector<float, 2>;
template Vector<float, 3>;

So far, I have tested it on Visual C++ (2008) and it compiles fine and the tests pass, but I am wondering if this is non-standard code.

Upvotes: 2

Views: 2152

Answers (2)

Yochai Timmer
Yochai Timmer

Reputation: 49269

It's OK.

Templates are a kind of way to tell the compiler to generate similar code for different types.
This is exactly what it's for.

Upvotes: 0

Puppy
Puppy

Reputation: 147036

No, that's perfectly legitimate and totally Standard. If you want to use a static variable in a templated class, there's no way you could possibly define all possible instantiations of it- those types may not even be nameable and therefore specializable. Hence, it's very necessary that template classes can have static variables defined for all possible uses.

Upvotes: 1

Related Questions