有什么优雅的方式吗?(类型参数包)
Is there any elegant way? (type parameter pack)
我想制作一个接受类型的函数,并通过循环或递归再次调用自己。
我已经尝试过的是下面,但它仅称为基本函数(用AModule
类称为基本功能,并且没有使用BModule.
class AModule {
};
class BModule {
};
auto main() -> int {
init<AModule, BModule>()
return 0;
}
template<typename Module>
void init() {
// BASE FUNCTION
// Do something
}
template<typename... Modules>
void init() {
(init<Modules>(), ...)
}
在您的示例中,您正在使用模板折叠,这是一个新的C 17功能,可允许您避免递归。
但是,为了避免名称碰撞,我建议以不同的方式调用基本版本;说 do_something()
template<typename Module>
void do_something() {
// BASE FUNCTION
// Do something
}
template<typename... Modules>
void init() {
(do_something<Modules>(), ...);
}
如果您真的想使用递归方式,则可以按照以下操作
template <int = 0>
void init ()
{
// stop recursion; do nothing
}
template <typename Head, typename ... Tail>
void init ()
{
// do something with Head
// recursively call init()
init<Tail...>();
}
诀窍是调用init<Tail...>();
,直到Tail...
不为空之前称为Head
/Tail...
递归版本。
当Tail...
为空时,init<Tail...>()
为init<>()
,因此Head
/Tail...
版本不再匹配(没有Head
),但与int = 0
版本匹配;因此,init<>()
成为init<0>()
,而无需地面案件停止递归。
在您的代码中(一旦修复了语法错误),两个init()
调用对于1个模板参数有效,因此调用模棱两可。通过进行多点呼叫需要至少2个参数,可以删除歧义。
// bogus type that just prints an error message including the type it is parameterized with
template<typename T>
struct printer;
template<typename Module>
void init() {
printer<Module>{}; // this is an error just to show you that it's getting called with both types
}
// only call this if it's called with 2 or more types, otherwise just use the other init()
template<typename T1, typename T2, typename... Modules>
void init() {
init<T1>();
init<T2>();
(init<Modules>(), ...);
}
class AModule {
};
class BModule {
};
auto main() -> int {
init<AModule, BModule>();
return 0;
}
live:https://godbolt.org/z/d-eh2g
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- 我在这里正确传递参数了吗?
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 我可以使用宏自动构建参数列表吗?
- 这种抽象模板矩阵类数据类型的方式好吗?
- 你能用同样的方式确定所有类类型的大小吗?
- 我可以将模板中的类型参数用于非类型参数吗?
- 有什么优雅的方式吗?(类型参数包)
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- 我可以省略头文件中智能指针的类型参数吗?
- 有清除类型的快捷方式吗
- 我应该对具有不同类型参数的类使用提升变体吗?
- 模板参数的c++部分类型推断-可能吗?
- 隐藏规则-参数/返回类型必须相同吗?
- 计算结果为"void..."的非类型参数包不是非法的吗?
- std::function 的模板参数(签名)不是其类型的一部分吗?