将临时结构作为模板参数传递

she*_*eep 6 c++ templates struct

我正在创建一个矢量类,并试图找出重用不同大小向量的最大代码量的方法.这是一个基本的例子:

template<typename T, unsigned int D>
class Vector
{
public:
    union {
        T v[D];
        struct {
            /* T x;
             * T y;
             * T z;
             * T w;
             */
        };
    };

    Vector()
    {
        for(unsigned int i=0; i<D; ++i)
            (*this)[i] = T(0);
    }
    Vector(T scalar)
    {
        for(unsigned int i=0; i<D; ++i)
            (*this)[i] = scalar;
    }

    inline T operator[](int i) { return (*this).v[i]; }
};
Run Code Online (Sandbox Code Playgroud)

我希望成员变量可以公开访问.例如:

Vector<float,2> vec;
printf("X: %.2f, Y: %.2f\n", vec.x, vec.y);
Run Code Online (Sandbox Code Playgroud)

我想做的是这样的事情:

template<typename T>
class Vector2 : public Vector<T,2, struct { T x; T y; }> {};

template<typename T>
class Vector3 : public Vector<T,2, struct { T x; T y; T z; }> {};
Run Code Online (Sandbox Code Playgroud)

并让它覆盖联合中的结构:

template<typename T, unsigned int D, struct C>
class Vector
{
public:
    union {
        T v[D];
        // Place the passed struct here
    };
};
Run Code Online (Sandbox Code Playgroud)

有没有可行的方法呢?如果可能的话,我不想使用标准库以外的任何东西.提前致谢.

编辑:在阅读完所有答案后,我明白我使用工会的方式是不正确的!感谢@MM指出这一点.我已经选择了不同的路线,但我选择了最适合我当时寻找的答案.再次感谢下面的所有欢迎回复!

W.F*_*.F. 1

如果我理解正确的话,您的主要目的是声明与模板类的数组元素相对应的字段顺序。您不能直接执行此操作,因为模板不接受内联类型作为参数。要解决此问题,您可以使用非类型模板参数将一些标签绑定到数组的给定索引:

#include <cstdio>
#include <unordered_map>
#include <utility>

struct Label { } x, y, z, w;

template <Label&... labels>
struct Pack { };

template <class, class>
struct VectorParent;

template <Label&... labels, size_t... Is>
struct VectorParent<Pack<labels...>, std::index_sequence<Is...>> {
   static std::unordered_map<Label *, size_t> label_map;
};

template <Label&... labels, size_t... Is>
std::unordered_map<Label *, size_t> VectorParent<Pack<labels...>, std::index_sequence<Is...>>::label_map = {{&labels, Is}...};

struct LabelNotFound { };

template <class T, size_t N, Label&... labels>
struct Vector:VectorParent<Pack<labels...>, std::make_index_sequence<sizeof...(labels)>> {
   static_assert(N == sizeof...(labels),
       "the cound of labels should corespond to the number of elements of the vector");
   using VectorParent<Pack<labels...>, std::make_index_sequence<sizeof...(labels)>>::label_map;
   T t[N];
   T &operator->*(Label& l) {
      auto it = label_map.find(&l);
      if (it == label_map.end())
         throw LabelNotFound{};
      return t[it->second];
   }
};

int main() {
    Vector<float,2,x,y> vec;
    vec->*x = 10.0f;
    printf("X: %.2f, Y: %.2f\n", vec->*x, vec->*y); // prints: X: 10.00, Y: 0.00
    //vec->*w = 10.1f; //would throw an exception LabelNotFound
}
Run Code Online (Sandbox Code Playgroud)