Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...