我有一个 vector 类,它有一些静态常量变量,如 ZERO
。现在,由于 vector 通常作为模板类实现(我的也不异常(exception)),我看到了很多这样的代码:
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)
我的问题是,我可以做这样的事情来避免为不同的类型重复代码吗:
template <typename T, unsigned int SIZE>
const Vector<T, SIZE> Vector<T, SIZE>::ZERO;
那能满足所有 future 的类型吗?如果不是,如果我将以下内容显式定义为各种类型的类,是否会有所不同:
template Vector<float, 2>;
template Vector<float, 3>;
到目前为止,我已经在 Visual C++ (2008) 上对其进行了测试,它编译良好并且测试通过,但我想知道这是否是非标准代码。
最佳答案
不,那是完全合法且完全标准的。如果您想在模板化类中使用静态变量,您不可能定义它的所有可能实例化——这些类型甚至可能无法命名,因此无法专门化。因此,模板类可以为所有可能的用途定义静态变量是非常必要的。
关于c++ - 定义模板类的静态常量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6397330/