Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic templates

Tags:

C++0x will allow template to take an arbitrary number of arguments. What is the best use of this feature other than implementing tuples ?

like image 630
Nicola Bonelli Avatar asked Nov 09 '08 17:11

Nicola Bonelli


People also ask

What are variadic templates C++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.

What is the use of variadic templates?

With the variadic templates feature, you can define class or function templates that have any number (including zero) of parameters. To achieve this goal, this feature introduces a kind of parameter called parameter pack to represent a list of zero or more parameters for templates.

What means variadic?

variadic (not comparable) (computing, mathematics, linguistics) Taking a variable number of arguments; especially, taking arbitrarily many arguments.

What is a parameter pack in C++?

Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.


2 Answers

  1. Type-safe printf
  2. Forwarding of arbitrary many constructor arguments in factory methods
  3. Having arbitrary base-classes allows for putting and removing useful policies.
  4. Initializing by moving heterogenous typed objects directly into a container by having a variadic template'd constructor.
  5. Having a literal operator that can calculate a value for a user defined literal (like "10110b").

Sample to 3:

template<typename... T> struct flexible : T... { flexible(): T()... { } }; 

Sample to 4:

struct my_container { template<typename... T> my_container(T&&... t) { } }; my_container c = { a, b, c }; 

Sample to 5:

template<char... digits> int operator "" b() { return convert<digits...>::value; } 

See this example code: here

like image 90
Johannes Schaub - litb Avatar answered Oct 15 '22 21:10

Johannes Schaub - litb


Maybe the talk by Andrei Alexandrescu on the Going Native 2012 event, will be of your interest:

Here is the video and Here the documentation.

like image 37
PaperBirdMaster Avatar answered Oct 15 '22 21:10

PaperBirdMaster