[英]Expand parameter pack for a function template
I have a function template as below. 我有如下功能模板。 The template argument needs to be explicitly given.
模板参数需要明确给出。
template<typename T>
void Func() {...};
I need to call this function for each type in a parameter pack: 我需要为参数包中的每种类型调用此函数:
template<typename... Inputs>
struct SetStruct{
void Set() {
// Call Func() here
}
};
Is there an easy way to expand the parameter pack? 有没有简单的方法来扩展参数包? I tried:
我试过了:
Func<Inputs>()...;
and 和
Func<Inputs>...();
But none of them works. 但是它们都不起作用。
I can only use C++11 :( 我只能使用C ++ 11 :(
Is there an easy way to expand the parameter pack?
有没有简单的方法来扩展参数包? I tried:
我试过了:
Func<Inputs>()...;
If you can use C++17, using the comma operator and template-folding 如果可以使用C ++ 17,请使用逗号运算符和模板折叠
((void)Func<Inputs>(), ...);
In C++11/C++14, using again the comma operator but in the context of initialization of an unused C-style array, something as follows 在C ++ 11 / C ++ 14中,再次使用逗号运算符,但是在初始化未使用的C样式数组的情况下,如下所示
template<typename... Inputs>
struct SetStruct{
void Set() {
using unused = int[];
(void)unused { 0, ((void)Func<Inputs>(), 0)... };
}
};
Observe that, in both cases, I've added a (void)
before the call to Func<>()
. 观察到,在两种情况下,我在调用
Func<>()
之前都添加了(void)
Func<>()
。
In your case it's useless (because your Func<>()
just return void
) but it's a sort of security belt in case of a function that return an object of a class that redefine the comma operator. 在您的情况下,它是无用的(因为
Func<>()
只是返回void
),但是在函数返回返回重新定义逗号运算符的类的对象的函数的情况下,它是一种安全带。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.