为模板传递非类型参数参数

ro_go

可能很愚蠢的问题:我正在尝试执行以下操作

template<unsigned int N>
class Foo{...}; // Define class Foo accordingly

int main(){
  for (unsigned int i = 0; i < 10; i++){
    Foo<i> f(3);
    f.show();
  }
  return 0;
}

可以想象,由于变量inot ,它不会编译const我知道这样做的原因是Foo<i>必须在编译时知道在非类型模板参数内分配的值,并且由于这里不是这种情况,因此它并不真正知道该怎么做。现在,我想知道是否有办法解决这个问题。当然,第一个想法是声明unsigned int N为Foo类的成员变量。

问题是:是否可以使用模板参数来实现上述预期的行为,还是必须将其声明unsigned int N为类的成员变量?

PS:我试图找到一个与问题相关的问题,但是我发现的问题与如何使用非类型模板参数有关,而在这些类型中它们并不能完全回答问题。因为他们没有提到这是可能的,所以我认为这是不可能完成的...

编辑。

是否可以执行以下操作?

template<unsigned int N>
class Foo{...}; // Define class Foo accordingly

int main(){
  std::vector<Foo> v; // I know it's better with shared_ptr, etc.. but to get the idea..
  for (unsigned int i = 0; i < 10; i++){
    Foo<i> f(3);
    f.show();
    v.push_back( f );
  }
  return 0;
}

v

我们没有for constexpr该语言,因此您不能直接这样做。您必须以某种方式模拟编译时for循环。有几种选择。

  1. 使用std::integer_sequence(C ++ 14)并int...打包:

    template<int i>
    void foo() {
        Foo<i> f(3);
        f.show();
    }
    
    template<int... is>
    void foo(std::integer_sequence<int, is...>) {
       (foo<is>(), ...);  // expands into foo<0>(), foo<1>(), ..., foo<9>()
    }
    
    foo(std::make_integer_sequence<unsigned int, 10>{});
    
  2. 使用递归和if constexpr(C ++ 17)模拟for循环:

    template<unsigned int i>
    void foo()
    {
        Foo<i> f(3);
        f.show();
    
        if constexpr (i + 1 < 10)
            foo<i + 1>();
    }
    
    foo<0>();
    
  3. 使用std::integral_constant(C ++ 11)和函数重载:

    void foo(std::integral_constant<unsigned int, 10>) {}
    
    template<unsigned int i>
    void foo(std::integral_constant<unsigned int, i>) {
        Foo<i> f(3);
        f.show();
        foo(std::integral_constant<unsigned int, i + 1>{});
    }
    
    foo(std::integral_constant<unsigned int, 0>{});
    

Foo<i>Foo<j>是不同的类型对于不同ij您不能将不同的类型放入std::vector如果is的在编译时已知,你可以做一个std::tupleFoo<i>秒。但这仍然会采用一些模板技巧。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章