C++ Interview Questions

22 Questions
C++ Programming

C++ Programming

Embedded SystemsIoTOther

Question 15

What are variadic templates in C++? Explain their syntax

Answer:

Variadic templates in C++ are a feature that allows functions and classes to accept a variable number of arguments. Introduced in C++11, variadic templates provide a way to write functions and classes that can handle an arbitrary number of template parameters, enabling more flexible and reusable code.

Syntax of Variadic Templates:
Variadic templates use an ellipsis (...) to indicate that a template can accept zero or more template parameters.

Example of Variadic Template Function:

template<typename... Args>
void print(Args... args) {
    (std::cout << ... << args) << std::endl; // Fold expression (C++17)
}

int main() {
    print(1, 2, 3, "Hello", 4.5); // Outputs: 123Hello4.5
    return 0;
}

In this example, the print function can accept any number of arguments of any type, and it uses a fold expression to print them.

Recursive Variadic Template Function (C++11):
Before C++17, variadic templates were often implemented using recursion.

template<typename T>
void print(T t) {
    std::cout << t << std::endl;
}

template<typename T, typename... Args>
void print(T t, Args... args) {
    std::cout << t << " ";
    print(args...);
}

int main() {
    print(1, 2, 3, "Hello", 4.5); // Outputs: 1 2 3 Hello 4.5
    return 0;
}

In this example, the print function uses recursion to handle multiple arguments. The base case prints a single argument, and the recursive case prints the first argument and then calls print with the remaining arguments.

Variadic Template Class:
Variadic templates can also be used with classes to create flexible and reusable data structures.

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

template<typename Head, typename... Tail>
class Tuple<Head, Tail...> : private Tuple<Tail...> {
    Head head;
public:
    Tuple(Head h, Tail... t) : head(h), Tuple<Tail...>(t...) {}

    Head getHead() const { return head; }

    Tuple<Tail...> getTail() const { return *this; }
};

int main() {
    Tuple<int, double, std::string> t(1, 2.3, "Hello");
    std::cout << t.getHead() << std::endl; // Outputs: 1
    std::cout << t.getTail().getHead() << std::endl; // Outputs: 2.3
    std::cout << t.getTail().getTail().getHead() << std::endl; // Outputs: Hello
    return 0;
}

In this example, the Tuple class template can store a variable number of elements of different types. It uses recursion to define the class structure, with each instantiation storing one element and inheriting from a Tuple holding the rest.

Advantages of Variadic Templates:

  1. Flexibility: Variadic templates can handle a variable number of arguments, making them highly flexible and reusable.
  2. Type Safety: Variadic templates maintain type safety, ensuring that all arguments are correctly handled and reducing the risk of type-related errors.
  3. Code Reduction: They can significantly reduce code duplication by providing a single template to handle multiple cases.

Use Cases:

  • Logging Functions: Variadic templates can be used to implement flexible logging functions that accept a variable number of arguments of different types.
  • Tuple Implementation: Variadic templates are often used to implement tuples, which are data structures that can hold a fixed number of elements of different types.
  • Forwarding Functions: They are useful for forwarding functions that need to pass a variable number of arguments to other functions.

Summary:
Variadic templates in C++ provide a powerful mechanism for handling functions and classes with a variable number of template parameters. They enhance flexibility, maintain type safety, and reduce code duplication. Understanding and utilizing variadic templates can lead to more generic, reusable, and efficient C++ code.

Recent job openings