使用模板包扩展时是否可以混合使用类型名和值?
例如,是否可以执行类似下面的 Bar 函数的操作?
template <typename T> class A
{
public:
void Foo()
{
printf( "A.Foo()\n" );
}
};
template <typename T, int x> class B
{
public:
void Foo()
{
printf( "B.Foo() with x = %d\n", x );
}
};
template <typename ClassType, typename... SubVals>
void Bar( ClassType<SubVals...> obj )
{
obj.Foo();
}
int main(int argc, char** argv)
{
A<int> a;
B<float, 3> b;
Bar<int>( a ); // This is allowed by the compiler
Bar<float, 3>( b ); // Compiler yells at this, though.
return 0;
}
最佳答案
您可以通过接受 int
的非类型参数包来解决这个问题,并让编译器为基于类型和零个或多个 模板化的类推导出第三个模板参数int
值。
template<typename T, int... Vals, template<typename, int...> class C>
void Bar(C<T, Vals...> obj)
{
obj.Foo();
}
可以像您的示例中那样使用显式模板参数调用:
A<int> a;
B<float, 3> b;
C<double, 1, 2, 3> c;
// explicit template args
Bar<int>(a);
Bar<float, 3>(b);
Bar<double, 1, 2, 3>(c);
或推导:
// deduced ones
Bar(a);
Bar(b);
Bar(c);
Live Demo (请注意,我保留了一个较早的工作原型(prototype),对某些人来说可能更容易理解)。
关于c++ - 将类型名称和值与模板包扩展混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35229882/