Ksawery
Ksawery

Reputation: 23

How are the C++11 variadic templates used in practice?

I recently came across the topic of C++11 variadic templates, and I'm wondering in what situations are they actually used? Are they primarily intended for recursion, where the number of parameters can vary (or is unknown)? Are there any other use cases apart from recursion?

Upvotes: 0

Views: 38

Answers (1)

Caleth
Caleth

Reputation: 63117

A good case for variadic templates is emplace (and emplace_back, emplace_front et.al.), i.e. constructing an element of a container in the storage the container allocated, with whatever constructor arguments the type takes.

Without that you would have to copy or move an existing object into that storage.

E.g.

std::vector<std::string> strings;
strings.emplace_back(10, 'a');

More generally, whenever you have something that wants to pass along arguments it was given to an expression that can take varying amounts of parameters, you'll want to use a variadic template.

Upvotes: 2

Related Questions