Zig*_*bra 2 c++ templates template-meta-programming variadic-templates c++11
我有一个功能模板如下.需要明确给出模板参数.
template<typename T>
void Func() {...};
Run Code Online (Sandbox Code Playgroud)
我需要为参数包中的每个类型调用此函数:
template<typename... Inputs>
struct SetStruct{
void Set() {
// Call Func() here
}
};
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来扩展参数包?我试过了:
Func<Inputs>()...;
Run Code Online (Sandbox Code Playgroud)
和
Func<Inputs>...();
Run Code Online (Sandbox Code Playgroud)
但它们都不起作用.
我只能使用C++ 11 :(
有没有简单的方法来扩展参数包?我试过了:
Func<Inputs>()...;
如果你可以使用C++ 17,使用逗号运算符和模板折叠
((void)Func<Inputs>(), ...);
Run Code Online (Sandbox Code Playgroud)
在C++ 11/C++ 14中,再次使用逗号运算符但在初始化未使用的C样式数组的上下文中,如下所示
template<typename... Inputs>
struct SetStruct{
void Set() {
using unused = int[];
(void)unused { 0, ((void)Func<Inputs>(), 0)... };
}
};
Run Code Online (Sandbox Code Playgroud)
请注意,在这两种情况下,我都(void)在调用之前添加了一个Func<>().
在你的情况下,它是无用的(因为你Func<>()只是返回void)但它是一种安全带,如果函数返回一个类的对象重新定义逗号运算符.