Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

c++11 - variadic template parameter pack expanding for function calls

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...