Tuples and variadic templates are both ways to work with a variable number of values, but they have different use cases.
Use tuples when:
std::get
, std::tuple_element
, etc.For example, a function that returns a player's name and score is a good candidate for a tuple:
std::tuple<std::string, int> getInfo(int id);
On the other hand, use variadic templates when:
For instance, a function that computes the sum of an arbitrary number of integers is a good fit for variadic templates:
template <typename... Args>
int sum(Args... args) {
return (... + args);
}
In this case, the sum
function accepts any number of arguments (captured by Args...
) and adds them together using a fold expression.
Sometimes, you can use the two techniques together. For example, you might have a variadic function template that forwards its arguments to another function as a tuple:
template <typename... Args>
void log(Args&&... args) {
std::tuple<Args...> data(
std::forward<Args>(args)...);
writeToLog(data);
}
Here, log
accepts any number of arguments, perfect forwards them to construct a tuple, and then passes that tuple to writeToLog
.
In summary, use tuples for bundling related values, and variadic templates for writing functions that operate on an arbitrary number of arguments in a uniform way. The two techniques can also be combined when needed.
Answers to questions are automatically generated and may not have been reviewed.
std::tuple
A guide to tuples and the std::tuple
container, allowing us to store objects of different types.