简体   繁体   English

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

[英]Creating a type with a variable number of members

Normally, when writing a Vector type, I do something like the following: 通常,在编写Vector类型时,我会执行以下操作:

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

...and then repeat for Vector3 , Vector4 and so on. ...然后重复执行Vector3Vector4等。

This made me wonder, is there a better way to do this? 这让我感到奇怪,是否有更好的方法可以做到这一点? For example, by expressing the number of members this type must have through sometime like a template. 例如,通过表达某种类型(例如模板)必须具有的成员数。 I'm not sure how the compiler would know how each member would be named, but just wanted to check in case I'm missing a wonderful trick. 我不确定编译器如何知道每个成员的命名方式,但只是想检查一下我是否错过了一个绝妙的技巧。

If your types are the same std::array can be helpful. 如果您的类型相同,则std::array可能会有所帮助。 You can then write your accessor functions as free-functions and get static assertions when the size is out of bounds. 然后,您可以将访问器函数编写为自由函数,并在大小超出范围时获取静态断言。 If your types are different, you could use std::tuple instead of 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM