Reputation: 2444
I have this 3D vector template
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
}
specialized for double float and int
class Vec3i : public Vec3TYPE< int, Vec3i > { };
class Vec3f : public Vec3TYPE< float, Vec3f > { };
class Vec3d : public Vec3TYPE< double, Vec3d > { };
I would like to do following things:
Initialize array of Vec3d by braces, like this:
Vec3f myVec3fs[2] = { {1.0f,2.0f,3.0f}, {3.0f,2.0f,1.0f} };
pass {1.0f,2.0f,3.0f} to a function as an argument of type Vec3f, like this:
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} );
Before i generalized my Vec3 class using templates ( i.e. when I defined Vec3d from scratch ), it was working just fine (at least with C++11 standard ).
Upvotes: 2
Views: 264
Reputation: 65620
Your issue is that by having Vec3X
inherit from Vec3TYPE
, you disqualify it as an aggregate type, so you can't just use aggregate initialization like you would like to. The way to fix this is to make your types aliases for the corresponding Vec3Type
instantiation:
//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>;
Upvotes: 3