可能很愚蠢的问题:我正在尝试执行以下操作
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;
}
可以想象,由于变量i
not ,它不会编译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;
}
我们没有for constexpr
该语言,因此您不能直接这样做。您必须以某种方式模拟编译时for
循环。有几种选择。
使用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>{});
使用递归和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>();
使用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>
是不同的类型对于不同i
和j
。您不能将不同的类型放入std::vector
。如果i
s的在编译时已知,你可以做一个std::tuple
的Foo<i>
秒。但这仍然会采用一些模板技巧。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句