首页 > 解决方案 > C++:我可以有非静态成员变量模板吗?

问题描述

我正在尝试编写一些代码,要求我std::array在容器类中有很多 s。这些数组都有不同的大小(如果重要的话,都是从 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++ 支持变量模板,但它似乎只适用于类中的静态成员。有没有可以表现相似的替代方案(最好尽可能少的开销)?

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

提前致谢。

标签: c++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>();

推荐阅读