如何在for循环中使用const变数来产生范本类别? [英] How to have a const variable in a for loop for the generation of template classes?

查看:104
本文介绍了如何在for循环中使用const变数来产生范本类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似

template <size_t N>
class A
{
    template <size_t N>
    someFunctions() {};
};

现在,我想创建该类的实例并在for循环中为一组许多值(如

Now I want to create instances of the class and call the functions in it in a for loop for a set of many values like

// in main()

int main()
{
    for (int i = 1; i <= 100; i++)
    {
        const int N = i;  // dont know how to do this
        A<N> a;
        a.functionCalls();
    }
}

如何执行此操作? 希望有一种方法可以做到这一点.

How to do this? Hoping for a method to do this.

推荐答案

这将需要称为template for的内容,该形式应为

This would require something called a template for which is the expected form expansion statements will take, which is something that look like a for loop but in reality is a templated block in a function that is instanciated multiple times.

当然,有一种解决方法.我们可以滥用通用Lambda来声明某种本地模板化的块并自行实例化:

Of course, there is a workaround. We can abuse generic lambdas to declare some sort of local templated block and instanciate it ourself:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F f) {
    (static_cast<void>(f(std::integral_constant<T, S>{})), ...);
}

此函数采用整数序列并实例化lambda F与序列的长度一样多的时间.

This function takes an integer sequence and instantiate the lambda F as many time as the length of the sequence.

它的用法如下:

for_sequence(std::make_index_sequence<100>(), [](auto N) { /* N is from 0 to 99 */
  A<N + 1> a; /* N + 1 is from 1 to 100 */
  a.functionCalls();
});

在这里,N可以作为模板参数发送,因为它是一个将constexpr转换运算符转换为整数类型的对象.更准确地说,它是一个std::integral_constant,其值不断增加.

Here, N can be sent as template parameter because it's an object that has a constexpr conversion operator to an integer type. More precisely, it's a std::integral_constant with an increasing value.

实时示例

这篇关于如何在for循环中使用const变数来产生范本类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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