← All CPP Flashcard Decks

Templates & Generic Programming Flashcards

7 cards from real CPP practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.

Read the first 7 Templates & Generic Programming flashcards as text
  1. What is the purpose of `std::enable_if` in template programming?

    Answer: To conditionally enable a template specialization based on a compile-time boolean

    `std::enable_if` uses SFINAE to include or exclude a template overload based on a compile-time boolean condition.

  2. Which of the following correctly declares a variadic template function?

    Answer: template void f(Args... args);

    The `...` after `typename` declares a parameter pack, and `Args... args` expands it in the function parameter list.

  3. What does `sizeof...(Args)` return in a variadic template?

    Answer: The number of types in the parameter pack

    `sizeof...(Args)` is a compile-time operator that returns the number of elements in a parameter pack.

  4. Which concept best describes SFINAE?

    Answer: Substitution Failure Is Not An Error — invalid template substitutions are silently discarded

    SFINAE means that when template argument substitution fails, the compiler removes that overload from consideration instead of issuing an error.

  5. What is a 'fold expression' introduced in C++17 for variadic templates?

    Answer: A compact syntax to apply a binary operator to all elements of a parameter pack

    Fold expressions allow applying operators like `+` or `&&` across all pack elements, e.g., `(args + ...)` sums the pack.

  6. What is the output of `template T add(T a, T b) { return a + b; }` called as `add(1, 2.0)`?

    Answer: Compilation error due to conflicting type deduction

    Template argument deduction fails because `T` is deduced as both `int` (from 1) and `double` (from 2.0), causing a compile error.

  7. What is an 'explicit instantiation' in C++ templates?

    Answer: A directive that forces the compiler to generate template code for a specific type

    Explicit instantiation (e.g., `template class MyClass;`) directs the compiler to generate the class for a given type, useful for controlling compilation units.