C++:我可以拥有非静态成员变量模板吗? [英] C++: Can I have non-static member variable templates?

查看:36
本文介绍了C++:我可以拥有非静态成员变量模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a bit of code that requires me to have a lot of std::arrays in a container class. These arrays are all of varying sizes (all consecutive from 2-16, if that matters), and there is exactly one of each size. I want to put them in a container class, and be able to access them with templates.

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

It's probably easier to explain with code. I want something like this:

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.像这样,但使用模板:

I'd like the code to expand out as if it just had 15 arrays in it, from 2-16. Like this, but with templates:

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++ 支持变量模板,但它似乎只适用于类中的静态成员.是否有其他替代方法可以表现类似(最好开销尽可能小)?

From what I understand, C++ supports variable templates, but it seems like it's only for static members in classes. Is there an alternative that could behave similarly (preferably with as little overhead as possible)?

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

If you need more information, please ask.

提前致谢.

推荐答案

我可以拥有非静态成员变量模板吗?

Can I have non-static member variable templates?

没有

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

However, you can use templates to generate a list of members like you describe. Here is an example using recursive inheritance:

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++:我可以拥有非静态成员变量模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆