可变参数模板参数包扩展为函数调用 [英] variadic template parameter pack expanding for function calls
问题描述
我正在寻找类似的东西:
template<类型名T>
void func(T t)
{
}
template<类型名... Parms>
void anyFunc(Parms ... p)
{
func< Parms>(p)...; //错误
func(p)...; //错误
}
如果参数包扩展是在另一个函数内完成的,则可以使用:
template<类型名T>
int some(T t)
{}
template<类型名... Parms>
void func(Parms ... p)
{}
template<类型名... Parms>
void somemore(Parms ... p)
{
func(some(p)...);
}
int main()
{
somemore(1,2,3,4,10,8,7, Hallo);
}
参数包扩展也适用于基类初始化程序的列表。 / p>
是否存在对返回 void的函数也有效的解决方案。上述变通办法将无法使用,而在使用函数调用时,在参数列表中返回void永远无法工作。
有什么想法吗?
不幸的是,正如您所注意到的那样,扩展参数包仅在解析器期望以逗号分隔的条目列表的某些情况下有效。逗号只是句法分隔符,而不是逗号运算符的上下文。
一个丑陋的解决方法:
func((some(p),0)...);
请注意,函数参数的求值顺序,也就是某些
调用是未指定的,因此您必须小心任何副作用。
I am looking for something like that:
template< typename T>
void func(T t)
{
}
template< typename... Parms>
void anyFunc( Parms... p)
{
func<Parms>(p)... ; //error
func(p)... ; //error
}
If the parameter pack expansion is done inside another function call it works:
template< typename T>
int some(T t)
{}
template< typename... Parms>
void func(Parms ...p)
{}
template< typename... Parms>
void somemore(Parms... p)
{
func( some(p)...);
}
int main()
{
somemore(1,2,3,4,10,8,7, "Hallo");
}
The parameter pack expansion will also work for a list of base class initializers.
Is there any solution which will also work for functions which will return 'void'. The above workaround will not, while using the function calls returning void inside a parameter list could never work.
Any ideas?
Unfortunately, as you noticed, expanding a parameter pack is only valid in certain contexts where the parser expects a comma-separated list of entries – contexts where the comma is just a syntactic separator, not the comma operator. This is arguably a deficiency in the current text.
An ugly workaround:
func((some(p), 0)...);
Do note that the evaluation order of function arguments, and thus the order of the some
invocations, is unspecified, so you have to be careful with any side effects.
这篇关于可变参数模板参数包扩展为函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!