Variadic Templates in C++
Introduction
Variadic templates are a powerful feature in C++ that allow functions and classes to accept a variable number of arguments. This feature was introduced in C++11 and is particularly useful for creating flexible and reusable code components. In this tutorial, we will explore the basics of variadic templates, their syntax, and practical examples to help you understand how to use them effectively.
Basic Syntax
In C++, a variadic template is defined using the ellipsis (...
) syntax. This allows you to create templates that can take any number of template parameters.
template<typename... Args>
void functionName(Args... args) {
// function body
}
In the example above, Args...
is a template parameter pack, and args...
is a function parameter pack. These packs can contain zero or more parameters of any type.
Example: Variadic Function Template
Let's create a simple example to demonstrate a variadic function template that takes multiple arguments and prints them:
#include <iostream>
template<typename... Args>
void print(Args... args) {
(std::cout << ... << args) << std::endl;
}
int main() {
print(1, 2, 3.14, "Hello, World!");
return 0;
}
In this example, the print
function uses a fold expression to print each argument to the standard output. When you run this program, the output will be:
Variadic Class Template
Variadic templates can also be used with classes. Here is an example of a variadic class template that can store a tuple of different types:
#include <iostream>
#include <tuple>
template<typename... Args>
class MyTuple {
public:
MyTuple(Args... args) : data(args...) {}
void print() {
printTuple(data);
}
private:
std::tuple<Args...> data;
template<std::size_t... I>
void printTupleImpl(const std::tuple<Args...>& t, std::index_sequence<I...>) {
((std::cout << std::get<I>(t) << " "), ...);
std::cout << std::endl;
}
void printTuple(const std::tuple<Args...>& t) {
printTupleImpl(t, std::index_sequence_for<Args...>{});
}
};
int main() {
MyTuple<int, double, const char*> myTuple(1, 2.5, "Hello");
myTuple.print();
return 0;
}
In this example, the MyTuple
class template uses a std::tuple
to store the arguments. The print
method prints the contents of the tuple using a helper function with index sequences.
When you run this program, the output will be:
Conclusion
Variadic templates are a versatile feature that can help you write more flexible and reusable code. By understanding how to use template parameter packs and function parameter packs, you can create functions and classes that handle a variable number of arguments. This tutorial has covered the basics, but there are many more advanced techniques and use cases to explore. Keep practicing and experimenting to fully harness the power of variadic templates in C++.