开发者

Defining static const variables of a template class

开发者 https://www.devze.com 2023-03-14 07:25 出处:网络
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:

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.


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.


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.

0

精彩评论

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

关注公众号