C++ Templates & Generics Quiz

C++
0 Passed
0% acceptance

40 in-depth questions covering C++ template fundamentals including function templates, class templates, template type deduction, non-type template parameters, and generic programming style — with 16 code examples to master compile-time polymorphism patterns.

40 Questions
~80 minutes
1

Question 1

What is a template in C++?

A
A compile-time mechanism for creating generic code that works with multiple types, where the compiler generates type-specific versions of the code during compilation
B
A way to create runtime polymorphic code
C
A way to define macros with type safety
D
A way to create dynamic arrays
2

Question 2

What is a function template in C++?

cpp
template<typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    int x = max(5, 3);        // T = int
    double y = max(5.5, 3.2); // T = double
    return 0;
}
A
A function definition that works with any data type, where the compiler generates specific versions for each type used at compile-time
B
A function that can change its return type at runtime
C
A function that works with void pointers
D
A function that is defined in a header file
3

Question 3

What is template argument deduction?

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

int main() {
    print(42);      // T deduced as int
    print(3.14);    // T deduced as double
    print("hello"); // T deduced as const char*
    return 0;
}
A
The compiler's ability to automatically determine template type parameters from function call arguments, eliminating the need for explicit type specification
B
The process of converting template code to machine code
C
The process of optimizing template instantiations
D
The process of checking template syntax
4

Question 4

What is a class template in C++?

cpp
template<typename T>
class Stack {
private:
    std::vector<T> data;
public:
    void push(T value) { data.push_back(value); }
    T pop() {
        T val = data.back();
        data.pop_back();
        return val;
    }
};

int main() {
    Stack<int> intStack;
    intStack.push(42);
    
    Stack<std::string> stringStack;
    stringStack.push("hello");
    return 0;
}
A
A class definition that can work with any data type, where the compiler generates specific class versions for each type used
B
A class that can change its member types at runtime
C
A class that inherits from multiple base classes
D
A class that uses void pointers for data storage
5

Question 5

What is template instantiation?

cpp
template<typename T>
T square(T x) { return x * x; }

int main() {
    int result1 = square(5);     // Instantiates square<int>
    double result2 = square(3.5); // Instantiates square<double>
    return 0;
}

// Compiler generates:
// int square<int>(int x) { return x * x; }
// double square<double>(double x) { return x * x; }
A
The process where the compiler generates specific code versions from template definitions by substituting actual types for template parameters
B
The process of compiling template code
C
The process of linking template libraries
D
The process of debugging template code
6

Question 6

What is a non-type template parameter?

cpp
template<typename T, size_t N>
class Array {
private:
    T data[N];  // N is compile-time constant
public:
    T& operator[](size_t index) { return data[index]; }
    size_t size() const { return N; }
};

int main() {
    Array<int, 5> arr;  // N = 5
    arr[0] = 42;
    std::cout << arr.size() << std::endl;  // 5
    return 0;
}
A
A template parameter that represents a compile-time constant value (like integers, pointers, or references) rather than a type, enabling metaprogramming with values
B
A template parameter that can change at runtime
C
A template parameter that represents a function
D
A template parameter that is automatically deduced
7

Question 7

What is template specialization?

cpp
// General template
template<typename T>
class Printer {
public:
    void print(T value) {
        std::cout << "Generic: " << value << std::endl;
    }
};

// Specialization for bool
template<>
class Printer<bool> {
public:
    void print(bool value) {
        std::cout << "Bool: " << (value ? "true" : "false") << std::endl;
    }
};

int main() {
    Printer<int> p1;
    p1.print(42);     // Uses general template
    
    Printer<bool> p2;
    p2.print(true);    // Uses specialization
    return 0;
}
A
Providing custom implementations for specific template parameter combinations, allowing optimized or different behavior for particular types
B
Converting a template to a non-template function
C
Making a template work with more types
D
Removing template parameters from a function
8

Question 8

What is partial template specialization?

cpp
// General template
template<typename T, typename U>
class Pair {
public:
    T first;
    U second;
};

// Partial specialization for when both types are the same
template<typename T>
class Pair<T, T> {
public:
    T first;
    T second;
    bool same() const { return first == second; }
};

int main() {
    Pair<int, double> p1;  // Uses general template
    Pair<int, int> p2;     // Uses partial specialization
    p2.first = 5;
    p2.second = 5;
    std::cout << p2.same() << std::endl;  // true
    return 0;
}
A
Specializing a template for some but not all template parameters, allowing different implementations based on partial type patterns
B
Specializing only function templates
C
Specializing templates at runtime
D
Making templates work with fewer parameters
9

Question 9

What is SFINAE (Substitution Failure is Not An Error)?

cpp
template<typename T>
class HasSize {
    typedef char Yes;
    typedef long No;
    
    template<typename U> static Yes test(decltype(&U::size));
    template<typename U> static No test(...);
    
public:
    static const bool value = sizeof(test<T>(0)) == sizeof(Yes);
};

class Container {
public:
    size_t size() const { return 0; }
};

int main() {
    std::cout << HasSize<Container>::value << std::endl;  // true
    std::cout << HasSize<int>::value << std::endl;       // false
    return 0;
}
A
A template metaprogramming technique where invalid template substitutions are silently ignored rather than causing compilation errors, enabling compile-time type trait detection
B
A way to make template errors more visible
C
A technique for runtime type checking
D
A way to prevent template instantiation
10

Question 10

What are variadic templates?

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

// Recursive expansion
void printAll() {}  // Base case

template<typename T, typename... Args>
void printAll(T first, Args... rest) {
    std::cout << first << " ";
    printAll(rest...);  // Recurse with remaining args
}

int main() {
    printAll(1, 2.5, "hello", true);  // Prints: 1 2.5 hello 1
    return 0;
}
A
Templates that accept a variable number of template arguments, enabling functions and classes that work with any number of parameters
B
Templates that can change their parameters at runtime
C
Templates that work with variable-sized arrays
D
Templates that can have optional parameters
11

Question 11

What is template metaprogramming?

cpp
// Compile-time factorial
template<size_t N>
struct Factorial {
    static const size_t value = N * Factorial<N-1>::value;
};

template<>
struct Factorial<0> {
    static const size_t value = 1;
};

int main() {
    std::cout << Factorial<5>::value << std::endl;  // 120 (computed at compile-time)
    return 0;
}
A
Using templates to perform computation at compile-time, generating code and values during compilation rather than runtime
B
Writing programs that modify themselves at runtime
C
Using templates to create runtime polymorphic code
D
Debugging template instantiation errors
12

Question 12

What is the difference between typename and class in template parameters?

cpp
template<typename T>  // Preferred
class Container {
    // ...
};

template<class U>     // Equivalent
class Container2 {
    // ...
};

// Inside templates, typename disambiguates dependent names
template<typename T>
void func() {
    typename T::iterator it;  // typename required
    // T::iterator it;       // Error: ambiguous
}
A
They are functionally identical for template parameters, but typename is preferred and also used to disambiguate dependent type names within template code
B
typename is used for class templates, class for function templates
C
class allows more types than typename
D
typename is deprecated in modern C++
13

Question 13

What is a dependent name in templates?

cpp
template<typename T>
class Container {
public:
    void func() {
        T::iterator it;     // Dependent name - could be type or value
        typename T::iterator it2;  // Disambiguated as type
        
        T::size();          // Dependent name - function call
        // No ambiguity here
    }
};

class MyClass {
public:
    typedef int iterator;
    static void size() {}
};
A
A name within a template that depends on a template parameter, requiring typename keyword to disambiguate when it refers to a type rather than a value or function
B
A name that depends on runtime values
C
A name that is defined outside the template
D
A name that causes template instantiation errors
14

Question 14

What is template argument deduction for functions?

cpp
template<typename T>
void func(T param) {}

template<typename T>
void func2(T& param) {}

int main() {
    int x = 5;
    const int cx = 10;
    
    func(x);      // T = int
    func(cx);     // T = int (const is adjusted)
    func2(x);     // T = int
    // func2(cx);  // Error: can't bind const int& to int&
    
    return 0;
}
A
The process where compilers infer template type parameters from function call arguments, following specific rules for type adjustment and reference binding
B
The process of manually specifying template arguments
C
The process of optimizing template functions
D
The process of checking template argument validity
15

Question 15

What is explicit template instantiation?

cpp
// In header file

template<typename T>
T multiply(T a, T b);

// In source file

template<typename T>
T multiply(T a, T b) { return a * b; }

// Explicit instantiations

template int multiply(int, int);
template double multiply(double, double);

int main() {
    int result = multiply(3, 4);  // Uses explicit instantiation
    return 0;
}
A
Manually forcing the compiler to generate specific template instantiations, often used to control compilation units and reduce compile times
B
Automatically generating template code
C
Preventing template instantiation
D
Converting templates to regular functions
16

Question 16

What is a template template parameter?

cpp
// Template template parameter example
// Allows templates to accept other templates as parameters
A
A template parameter that itself is a template, allowing templates to accept other templates as parameters for generic container adaptation
B
A parameter that can be any type
C
A parameter that represents a function
D
A parameter that is automatically deduced
17

Question 17

What is generic programming in C++?

A
Writing code that works with any type that satisfies certain requirements, using templates to achieve type-safe, reusable algorithms and data structures
B
Writing code that uses void pointers
C
Writing code that works only with built-in types
D
Writing code that changes types at runtime
18

Question 18

What is the difference between templates and macros?

A
Templates provide type safety, scope rules, and compile-time type checking, while macros are text substitution without type safety or scoping
B
They are identical in functionality
C
Macros are safer than templates
D
Templates are only used for functions
19

Question 19

What is template recursion?

cpp
// Compile-time Fibonacci using template metaprogramming
// Templates generate code at compile-time for computation
A
Using recursive template instantiation to perform compile-time computation, where templates call themselves with different parameters to build complex computations
B
Calling template functions recursively at runtime
C
Creating circular template dependencies
D
Debugging template instantiation
20

Question 20

What is the difference between function templates and class templates?

A
Function templates generate functions, class templates generate classes, with different syntax and instantiation rules
B
They are identical in functionality
C
Function templates are more powerful than class templates
D
Class templates can only have one parameter
21

Question 21

What is the difference between templates and inheritance for code reuse?

A
Templates provide compile-time code generation with no runtime overhead, inheritance provides runtime polymorphism with virtual dispatch overhead
B
They are identical approaches
C
Inheritance is always better than templates
D
Templates require inheritance
22

Question 22

What is the difference between templates and generics in other languages?

A
C++ templates use compile-time code generation with potential code bloat, other languages use runtime type erasure or JIT compilation for generics
B
They are identical concepts
C
C++ templates are more powerful than generics
D
Generics are only used in Java and C#
23

Question 23

What is the difference between template parameters and function parameters?

A
Template parameters are compile-time constants determining code generation, function parameters are runtime values passed to instantiated functions
B
They are identical concepts
C
Template parameters can change at runtime
D
Function parameters determine code generation
24

Question 24

What is the difference between template specialization and overloading?

A
Specialization provides custom implementations for specific types, overloading provides different implementations for different argument patterns
B
They are identical concepts
C
Specialization is only for functions
D
Overloading requires templates
25

Question 25

What is the difference between template metaprogramming and runtime programming?

A
Metaprogramming performs computation during compilation to generate code, runtime programming performs computation during execution
B
They are identical approaches
C
Runtime programming is faster than metaprogramming
D
Metaprogramming requires runtime execution
26

Question 26

What is the difference between templates and constexpr?

A
Templates generate different code for different types, constexpr enables compile-time computation within functions for any type
B
They are identical concepts
C
Templates are more powerful than constexpr
D
constexpr requires templates
27

Question 27

What is the difference between template instantiation and template compilation?

A
Instantiation generates specific code from templates, compilation converts that code to machine language
B
They are identical processes
C
Instantiation happens at runtime
D
Compilation generates template code
28

Question 28

What is the difference between template arguments and template parameters?

A
Parameters are placeholders in template definitions, arguments are actual types/values provided during instantiation
B
They are identical concepts
C
Arguments are defined in templates
D
Parameters are provided during instantiation
29

Question 29

What is the difference between template deduction and template specification?

A
Deduction automatically infers types from arguments, specification explicitly provides types during instantiation
B
They are identical processes
C
Specification is automatic
D
Deduction requires explicit types
30

Question 30

What is the difference between template specialization and template overloading?

A
Specialization provides alternative implementations for specific types, overloading provides multiple implementations for different argument patterns
B
They are identical concepts
C
Specialization works with classes only
D
Overloading requires specialization
31

Question 31

What is the difference between template metaprogramming and functional programming?

A
Metaprogramming uses types and templates for compile-time computation, functional programming uses functions and immutability for runtime computation
B
They are identical paradigms
C
Functional programming requires templates
D
Metaprogramming requires functional programming
32

Question 32

What is the difference between template recursion and runtime recursion?

A
Template recursion generates code at compile-time through recursive instantiation, runtime recursion executes function calls during program execution
B
They are identical concepts
C
Runtime recursion is faster than template recursion
D
Template recursion requires runtime execution
33

Question 33

What is the difference between template code bloat and runtime code size?

A
Template bloat creates multiple code versions for different types, runtime size is the final executable size after optimization and linking
B
They are identical concerns
C
Runtime code size is always larger
D
Template bloat doesn't affect executable size
34

Question 34

What is the difference between template debugging and runtime debugging?

A
Template debugging deals with compilation errors and instantiation issues, runtime debugging deals with execution behavior and logic errors
B
They are identical processes
C
Runtime debugging is easier than template debugging
D
Template debugging doesn't exist
35

Question 35

What is the difference between template libraries and runtime libraries?

A
Template libraries are header-only with compile-time instantiation, runtime libraries are compiled binaries with runtime linking
B
They are identical concepts
C
Runtime libraries are faster than template libraries
D
Template libraries require runtime linking
36

Question 36

What is the difference between template performance and runtime performance?

A
Template performance includes compilation time and code size, runtime performance includes execution speed and memory usage
B
They are identical concerns
C
Runtime performance is more important
D
Template performance doesn't affect runtime
37

Question 37

What is the difference between template evolution and runtime evolution?

A
Template evolution requires recompilation of all dependent code, runtime evolution can occur through dynamic loading and plugin systems
B
They are identical processes
C
Runtime evolution is easier than template evolution
D
Template evolution doesn't require recompilation
38

Question 38

What is the difference between template constraints and runtime constraints?

A
Template constraints are checked at compile-time through SFINAE and concepts, runtime constraints are checked during execution with assertions and exceptions
B
They are identical concepts
C
Runtime constraints are more reliable
D
Template constraints don't exist
39

Question 39

What is the difference between template documentation and runtime documentation?

A
Template documentation focuses on type requirements and instantiation rules, runtime documentation focuses on behavior and API usage
B
They are identical approaches
C
Runtime documentation is more complex
D
Template documentation doesn't include behavior
40

Question 40

What are the fundamental principles for effective template design in C++?

A
Use templates for generic algorithms with minimal assumptions, provide clear type requirements, consider code bloat vs runtime performance trade-offs, use SFINAE and concepts for constraints, and document template parameter requirements clearly
B
Make all code templates for maximum flexibility
C
Avoid templates and use inheritance instead
D
Use void pointers for all generic code

QUIZZES IN C++