创建具有可变数量成员的类型

时间:2014-07-22 14:30:59

标签: c++ templates

通常,在编写Vector类型时,我会执行以下操作:

template <typename Type>
struct Vector2{
    Type x;
    Type y;
};

...然后重复Vector3Vector4等等。

这让我想知道,有更好的方法吗?例如,通过表达此类型必须具有的成员数量,例如模板。我不确定编译器如何知道如何命名每个成员,但只是想检查以防我错过了一个很棒的技巧。

1 个答案:

答案 0 :(得分:1)

如果您的类型相同std::array可能会有所帮助。那你可以 将访问器函数编写为自由函数并获取静态函数 当大小超出界限时的断言。如果您的类型是 不同的是,您可以使用std::tuple代替std::array

#include <array>
#include <iostream>

namespace X {

template<typename T>
using Vector2 = std::array<T, 2>;

template<typename T>
using Vector3 = std::array<T, 3>;

// named accessors, you might want to make the accepted parameter more
// specific, e.g. std::array<T,I>
template<typename T>
decltype(auto) x(T&& t) { return std::get<0>(std::forward<T>(t)); }
template<typename T>
decltype(auto) y(T&& t) { return std::get<1>(std::forward<T>(t)); }
template<typename T>
decltype(auto) z(T&& t) { return std::get<2>(std::forward<T>(t)); }

}

int main()
{
  X::Vector2<int> v = {1, 2};
  // you can use [] syntax
  std::cout << v[0] << " " << v[1] << std::endl;
  // or named access
  X::x(v) = 2;
  X::z(v); // static assertion triggered
  return 0;
}