通过模板包扩展混合类型名称和值
Mixing typenames and values with template pack expansion
使用模板包扩展时是否可以混合使用类型名称和值?
例如,是否可以执行类似于下面的 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 = %dn", 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);
现场演示(注意我留下了早期的工作原型,对于某些人来说可能更容易遵循)。
相关文章:
- 使用 Boost.Spirit 解析具有混合数据类型的 OBJ 文件?
- C++以迭代方式搜索混合类型地图
- 处理一般情况混合类型和非类型的可变参数模板
- 使用 pybind11 混合类型转换和不透明类型
- 如何处理使用不同类型索引的不同库(例如 stl 和 eigen3)的混合(size_t、int、..)
- C++中混合数据类型的算术运算
- 混合模板类型的模板参数包(std::使用可选参数重新创建函数)
- 重值引用不是将类型和类别混合在一起吗?
- 模板模板参数,具有混合类型和非类型variadic参数
- C 混合蛋白,检查模板类型是否实现了某些混合蛋白
- 混合类型的Cython 2-D Numpy阵列为void **
- 在 C/C++ 中,混合类型整数数学所需的最小类型向上转换是多少?
- 混合类型的Boost运算符-转换和私有成员
- 混合可变参数模板值和可变参数推导类型
- C++具有混合分隔符和数据类型的文件输入
- 具有混合数据类型的条件运算符
- C++具有导致溢出的混合整数类型的算术
- 混合模板化参数类型
- 在 C++ 中混合数据类型令人困惑
- 检查嵌套混合中每个类的类型特征