gpt4 book ai didi

C++:我可以有非静态成员变量模板吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:33:48 26 4
gpt4 key购买 nike

我正在尝试编写一些代码,要求我在容器类中有很多 std::array。这些数组的大小各不相同(如果重要的话,都是从 2 到 16 连续的),并且每种大小都有一个。我想将它们放在一个容器类中,并能够使用模板访问它们。

用代码解释可能更容易。我想要这样的东西:

class ContainerClass {

public:
// I want to declare some number of arrays right here, all of different
// sizes, ranging from 2-16. I'd like to be able to access them as
// arr<2> through arr<16>.

// This code gives a compiler error, understandably.
// But this is what I'd think it'd look like.
template <size_t N> // I also need to find a way to restrict N to 2 through 16.
std::array<int, N> arr;

// An example method of how I want to be able to use this.
template <size_t N>
void printOutArr() {
for (int i = 0; i < N; i++) {
std::cout << arr<N>[i] << std::endl;
}
}
};

我希望代码扩展为好像其中只有 15 个数组,从 2 到 16。像这样,但使用模板:

class ContainerClass {

public:
std::array<int, 2> arr2;
std::array<int, 3> arr3;
std::array<int, 4> arr4;
std::array<int, 5> arr5;
// ... and so on.
};

据我了解,C++ 支持变量模板,但它似乎仅适用于类中的静态成员。是否有一种替代方法可以表现出类似的行为(最好是开销尽可能小)?

如果您需要更多信息,请询问。

提前致谢。

最佳答案

Can I have non-static member variable templates?

没有。

但是,您可以使用模板生成您所描述的成员列表。下面是一个使用递归继承的例子:

template<class T, std::size_t base, std::size_t size>
class Stair;

template<class T, std::size_t base>
class Stair<T, base, base> {};

template<class T, std::size_t base, std::size_t size>
class Stair : Stair<T, base, size - 1> {
protected:
std::array<T, size> arr;
public:
template<std::size_t s>
std::array<T, s>& array() {
return Stair<T, base, s>::arr;
}
};

int main()
{
Stair<int, 2, 10> s;
auto& arr = s.array<9>();

关于C++:我可以有非静态成员变量模板吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52857352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com