定义模板类的静态常量变量 [英] Defining static const variables of a template class

查看:709
本文介绍了定义模板类的静态常量变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量类,它有一些静态常量变量,例如 ZERO 。现在因为vector通常被实现为一个模板类(我也不例外),我看到很多这样的代码:

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)

我的问题是,我可以这样做,以避免重复的代码只是一个不同的类型: p>

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

到目前为止,我已经测试了它在Visual C ++(2008),它编译良好,测试通过,但我想知道这是不是标准的代码。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆