C++11 What is Variadic template and How it works?

Variadic templates are a feature introduced in C++11 that allows functions and classes to take a variable number of arguments of different types. The syntax for a variadic template is to use an ellipsis ... after the type parameter. Here is an example of a variadic function that takes a variable number of arguments and returns their sum:

template<typename T>
T sum(T value) {
    return value;
}

template<typename T, typename... Args>
T sum(T value, Args... args) {
    return value + sum(args...);
}
The first template function is the base case, which simply returns the value passed in. The second template function is the recursive case, which adds the current value to the sum of the remaining arguments. Variadic templates can also be used to create variadic classes. Here is an example of a variadic tuple class that stores a tuple of values of different types:

template<typename... Ts>
class Tuple {};

template<typename T, typename... Ts>
class Tuple<T, Ts...> : public Tuple<Ts...> {
public:
    Tuple(T value, Ts... args) : Tuple<Ts...>(args...), m_value(value) {}

    T get() { return m_value; }

private:
    T m_value;
};
In this example, the Tuple class is defined recursively. The base case is an empty tuple, and the recursive case is a tuple that stores a single value of type T followed by a tuple of types Ts... The get() method returns the value stored in the current tuple.

Comments

Popular posts from this blog

C++ data structure and containers and their operation with time complexity

Copyable and non-copyable Objects in C++

Prepare for your next C++ interview