我有以下的矢量的類(矢量作爲在空間,而不是陣列):匿名結構與啓用/禁用
template<typename T0, size_t S, typename = typename std::enable_if<std::is_arithmetic<T0>::value && (S > 1 && S < 5)>::type>
struct Vec
{
using value_type = T0;
using vector_type = Vec<T0, S>;
using array_type = std::array<T0, S>;
using index_type = size_t;
using size_type = size_t;
enum { num_components = S };
array_type v;
};
,使得我可以使一個向量類型2,3或4個要素:
template<typename T0>
using Vec2 = Vec<T0, 2>;
template<typename T0>
using Vec3 = Vec<T0, 3>;
template<typename T0>
using Vec4 = Vec<T0, 4>;
訪問形式爲v [0],v [1]等(爲了簡潔起見,我不包括[]運算符重載)。有時候我更喜歡x,y等等,但不想要額外的「。」。從命名聯盟中的結構。所以使用Visual Studio 2013的非標準的「功能」,試圖使用匿名聯合,僅使值,如果S(尺寸)爲2,3或4,如下所示:
template<typename T0, size_t S, typename = typename std::enable_if<std::is_arithmetic<T0>::value && (S > 1 && S < 5)>::type>
struct Vec
{
using value_type = T0;
using vector_type = Vec<T0, S>;
using array_type = std::array<T0, S>;
using index_type = size_t;
using size_type = size_t;
enum { num_components = S };
union
{
array_type v;
template<typename = typename std::enable_if<S == 2>::type>
struct
{
value_type x, y;
};
template<typename = typename std::enable_if<S == 3>::type>
struct
{
value_type x, y, z;
};
template<typename = typename std::enable_if<S == 4>::type>
struct
{
value_type x, y, z, w;
};
};
};
不幸的是這給出了我有以下錯誤:
**error C2332: 'struct' : missing tag name**
而在某種程度上,我想它是。有什麼方法可以實現我在這裏嘗試的嗎?我確定啓用/禁用anoymous結構幾乎肯定會給編譯器一個migrane。我可以像這樣使用匿名聯合,如果我給結構一個名字當然。
它是value_type,所以我可以爲同一元素編寫myvec.v [0]或myvec.x。當然,2D矢量沒有Z,3D矢量沒有W,所以我希望能以某種方式禁用這些功能。 – Robinson
哦,你是對的,對不起。將解決。 – Robinson