我有这个3D矢量模板
template <class TYPE, class VEC>
class Vec3TYPE{
public:
union{
struct{ TYPE x,y,z; };
struct{ TYPE a,b,c; };
TYPE array[3];
};
inline void set( const VEC& a ){ x=a.x; z=a.y; z=a.z; };
inline void add( const VEC& a ){ x+=a.x; z+=a.y; z+=a.z; };
// + some other methods .... doesn't matter
}
专门用于double float和int
class Vec3i : public Vec3TYPE< int, Vec3i > { };
class Vec3f : public Vec3TYPE< float, Vec3f > { };
class Vec3d : public Vec3TYPE< double, Vec3d > { };
我想做以下事情:
用大括号初始化Vec3d数组,如下所示:
Vec3f myVec3fs[2] = { {1.0f,2.0f,3.0f}, {3.0f,2.0f,1.0f} };
将{1.0f,2.0f,3.0f}传递给函数作为Vec3f类型的参数,如下所示:
float someFunc( const Vec3f& a );
float result = someFunc( {1.0f,2.0f,3.0f} );
Vec3d myVec3f;
myVec3f.set( {3.0f,2.0f,1.0f} );
myVec3f.add( {1.0f,2.0f,3.0f} );
在我使用模板推广我的Vec3类之前(即当我从头开始定义Vec3d时),它工作正常(至少使用C ++ 11标准)。
答案 0 :(得分:3)
您的问题是,Vec3X
继承Vec3TYPE
后,您将其取消作为聚合类型的资格,因此您无法像您希望的那样使用聚合初始化。解决此问题的方法是为相应的Vec3Type
实例化创建别名类型:
//just take one template param, we can work out what the second was
template <class TYPE>
class Vec3TYPE{
//typedef VEC here
using VEC = Vec3TYPE<TYPE>;
//same as you had previously
};
//alias instead of inherit
using Vec3i = Vec3TYPE<int>;
using Vec3f = Vec3TYPE<float>;
using Vec3d = Vec3TYPE<double>;