使用模板包扩展时是否可以混合使用类型名和值?
例如,是否可以执行下面的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;
}
答案 0 :(得分: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(注意我留在之前的工作原型中,对某些人来说可能更容易理解。)