C ++ is interesting: execute a separate function for each parameter in the Variable Parameter template. The parameter Template

Source: Internet
Author: User

C ++ is interesting: execute a separate function for each parameter in the Variable Parameter template. The parameter Template

For Variable Parameter templates that appear after c ++ 11, we generally process all the parameters in a unified manner. When you need to perform different operations for each parameter or call different functions, the syntax is not directly supported.

Variable Parameter template syntax:

template<typename...T>void function(T...args){}

If you want to execute a function for each parameter indicated by args separately, you can use the following method:

void print(int arg){}template <typename... T>void callfn(void(*fn)(T...args)){    using expand_type = int[];    expand_type{ (print(args), 0)... };}void fn1(int a1, int a2, int a3){}void fn2(int a1, int a2, int a3, int a4, int a5, int a6){}int main(){    callfn(fn1);    callfn(fn2);    return 0;}

In this way, the print function can be called once for each parameter of the function passed in by callfn.

We should first think of using this method.

print(args);...

However, the syntax does not work. Fortunately, we can use the initialization list Syntax:

using expand_type = int[];expand_type{ (print(args), 0)... };

(Print (args), 0) 0 is used to generate a positive number for the brackets, so that the initialization list is legal.

 

Reference 1: https://stackoverflow.com/questions/17339789/how-to-call-a-function-on-all-variadic-template-args

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.