C++ Templates - MCQs

1 min read

1. What is the primary purpose of templates in C++?

a) To execute code at runtime
b) To write generic, reusable code that works with different data types
c) To manage dynamic memory allocation
d) To handle exceptions
Correct Answer: b) To write generic, reusable code that works with different data types
Explanation:
Templates allow functions and classes to operate with generic types, enabling code reuse without sacrificing type safety or performance.

2. Which keywords can be used to declare a template type parameter?

a) class and typename
b) struct and class
c) type and typename
d) template and class
Correct Answer: a) class and typename
Explanation:
In C++, both 'class' and 'typename' keywords can be used interchangeably to declare a type parameter in a template definition.

3. Is there any functional difference between using 'class' and 'typename' in a template parameter list?

a) Yes, 'class' only accepts class types
b) Yes, 'typename' only accepts primitive types
c) No, they are completely interchangeable in this context
d) Yes, 'typename' is faster
Correct Answer: c) No, they are completely interchangeable in this context
Explanation:
When declaring a template type parameter, 'class' and 'typename' mean exactly the same thing and can accept any type, including primitives and classes.

4. How do you declare a basic function template?

a) template<T> void func(T val);
b) template<typename T> void func(T val);
c) generic<T> void func(T val);
d) void func<T>(T val);
Correct Answer: b) template<typename T> void func(T val);
Explanation:
The correct syntax requires the 'template' keyword followed by angle brackets containing the type parameter, and then the function declaration.

5. How do you declare a basic class template?

a) class template<T> MyClass {};
b) template<class T> class MyClass {};
c) generic<T> class MyClass {};
d) template<T> class MyClass {};
Correct Answer: b) template<class T> class MyClass {};
Explanation:
A class template is declared using the 'template' keyword, followed by the template parameters in angle brackets, and then the class definition.

6. What is template argument deduction?

a) Manually specifying template arguments
b) The compiler automatically determining template arguments from the function arguments
c) Removing template arguments from the code
d) Converting template arguments to runtime variables
Correct Answer: b) The compiler automatically determining template arguments from the function arguments
Explanation:
Template argument deduction is the process where the compiler infers the template types based on the types of the arguments passed to a function template.

7. What happens if the compiler cannot deduce template arguments for a function template?

a) It uses int as a default
b) It generates a runtime error
c) It results in a compilation error
d) It ignores the template parameters
Correct Answer: c) It results in a compilation error
Explanation:
If the compiler cannot deduce the template arguments and no defaults are provided, it will fail to compile the code.

8. How do you explicitly specify template arguments for a function template?

a) func(int, 5);
b) func<int>(5);
c) func<type=int>(5);
d) func[ int ](5);
Correct Answer: b) func<int>(5);
Explanation:
Explicit template arguments are provided in angle brackets immediately after the function name and before the function argument parentheses.

9. What is explicit instantiation of a template?

a) Forcing the compiler to generate the code for a specific template specialization
b) Deleting a template instantiation
c) Defining a template without a body
d) Using a template at runtime
Correct Answer: a) Forcing the compiler to generate the code for a specific template specialization
Explanation:
Explicit instantiation tells the compiler to generate the code for a specific set of template arguments, which is useful for reducing compilation times in large projects.

10. Where must the definition of a template typically be placed?

a) In a source (.cpp) file only
b) In a header (.h or .hpp) file
c) In the main function
d) In a separate binary file
Correct Answer: b) In a header (.h or .hpp) file
Explanation:
Because templates are instantiated at compile time, their full definitions must be visible to the compiler in every translation unit where they are used, typically via header files.

11. What is template specialization?

a) Providing a specific implementation for a particular set of template arguments
b) Deleting a template
c) Making a template private
d) Converting a template to a macro
Correct Answer: a) Providing a specific implementation for a particular set of template arguments
Explanation:
Template specialization allows you to define custom behavior for a template when it is instantiated with specific types or values.

12. What is the syntax for a full (explicit) specialization of a class template?

a) template<class T> class MyClass<int> {};
b) template<> class MyClass<int> {};
c) specialize<class int> class MyClass {};
d) template<int> class MyClass {};
Correct Answer: b) template<> class MyClass<int> {};
Explanation:
Full specialization uses an empty template parameter list 'template' followed by the class name with the specific arguments filled in.

13. Can you partially specialize a function template in C++?

a) Yes, using the 'partial' keyword
b) Yes, just like class templates
c) No, function templates cannot be partially specialized
d) No, function templates cannot be specialized at all
Correct Answer: c) No, function templates cannot be partially specialized
Explanation:
C++ does not allow partial specialization of function templates. You can only fully specialize them or use function overloading to achieve similar effects.

14. What is partial specialization?

a) Specializing a template for a specific subset of its parameters while leaving others generic
b) Specializing only the methods of a class template
c) Specializing a template for all pointer types
d) Removing half of the template parameters
Correct Answer: a) Specializing a template for a specific subset of its parameters while leaving others generic
Explanation:
Partial specialization allows you to provide a specialized implementation for a template when some, but not all, template arguments match a specific pattern or type.

15. Which of the following can be used as a non-type template parameter?

a) A floating-point literal
b) An integer constant expression
c) A std::string object
d) A dynamically allocated array
Correct Answer: b) An integer constant expression
Explanation:
Non-type template parameters must be constant expressions. Historically, this was limited to integral types, enums, and pointers, though C++20 expanded this to include floating-point and class types with constexpr constructors.

16. What does SFINAE stand for?

a) Substitution Failure Is Not An Error
b) Standard Function Interface And Execution
c) Static Function Initialization And Evaluation
d) Substitution Function In Native Execution
Correct Answer: a) Substitution Failure Is Not An Error
Explanation:
SFINAE is a principle in C++ where if a substitution of template arguments fails, the compiler simply discards that specific overload instead of throwing a compilation error.

17. Which standard library utility is commonly used to implement SFINAE?

a) std::is_valid
b) std::enable_if
c) std::sfinae
d) std::type_check
Correct Answer: b) std::enable_if
Explanation:
std::enable_if is a type trait used in SFINAE to conditionally remove functions or classes from overload resolution based on compile-time conditions.

18. What is two-phase name lookup in templates?

a) Looking up names in the syntax tree and then the semantic tree
b) Phase 1 checks non-dependent names at definition time, Phase 2 checks dependent names at instantiation time
c) Looking up names in the header file and then the source file
d) Looking up names in the local scope and then the global scope
Correct Answer: b) Phase 1 checks non-dependent names at definition time, Phase 2 checks dependent names at instantiation time
Explanation:
In phase 1, the compiler checks names that do not depend on template parameters. In phase 2, after the template is instantiated with specific types, it checks names that depend on those parameters.

19. When must the 'typename' keyword be used in a template?

a) Before every variable declaration
b) Before a dependent name that represents a type
c) Before a function call
d) Before a template instantiation
Correct Answer: b) Before a dependent name that represents a type
Explanation:
When a name depends on a template parameter and refers to a type (like T::iterator), you must prefix it with 'typename' to tell the compiler to treat it as a type.

20. What is a dependent name?

a) A name that depends on a runtime variable
b) A name whose meaning depends on a template parameter
c) A name that is inherited from a base class
d) A name that is dynamically allocated
Correct Answer: b) A name whose meaning depends on a template parameter
Explanation:
A dependent name is an identifier in a template whose type or value cannot be determined until the template is instantiated with specific arguments.

21. How do you access a member of a dependent base class?

a) Directly by its name
b) Using this-> or Base<T>::
c) Using the typename keyword
d) Using the template keyword
Correct Answer: b) Using this-> or Base<T>::
Explanation:
Because base classes of class templates are dependent types, their members are not visible by default. You must qualify them using 'this->' or the base class name to make them dependent.

22. What is a variadic template?

a) A template that takes a variable number of template arguments
b) A template that returns multiple values
c) A template that can change its type at runtime
d) A template that uses virtual functions
Correct Answer: a) A template that takes a variable number of template arguments
Explanation:
Variadic templates allow templates to accept any number of arguments of any type, enabling highly flexible generic programming.

23. What symbol is used to denote a template parameter pack?

a) *
b) &
c) ...
d) ->
Correct Answer: c) ...
Explanation:
The ellipsis (...) is used to declare a parameter pack, which can accept zero or more template arguments.

24. What is pack expansion?

a) Allocating memory for a parameter pack
b) Expanding a parameter pack into its individual arguments using the ellipsis
c) Deleting a parameter pack
d) Converting a parameter pack to an array
Correct Answer: b) Expanding a parameter pack into its individual arguments using the ellipsis
Explanation:
Pack expansion is the process of expanding a parameter pack into a comma-separated list of its individual elements, typically by following the pack name with an ellipsis.

25. What does the 'sizeof...' operator do?

a) Returns the memory size of a parameter pack
b) Returns the number of elements in a parameter pack
c) Returns the size of the largest element in a pack
d) Returns the size of the template class
Correct Answer: b) Returns the number of elements in a parameter pack
Explanation:
The 'sizeof...' operator is a compile-time operator that returns the number of elements in a template parameter pack.

26. What are fold expressions in C++17?

a) Expressions that compress data
b) A syntax to reduce (fold) a parameter pack over a binary operator
c) Expressions that hide template parameters
d) Expressions that evaluate at runtime
Correct Answer: b) A syntax to reduce (fold) a parameter pack over a binary operator
Explanation:
Fold expressions provide a concise way to apply a binary operator (like +, *, ||) across all elements of a parameter pack.

27. How many types of fold expressions are there in C++?

a) Two
b) Three
c) Four
d) Five
Correct Answer: c) Four
Explanation:
There are four types of fold expressions: unary right fold, unary left fold, binary right fold, and binary left fold.

28. What is a template template parameter?

a) A template that takes another template as an argument
b) A template that generates another template
c) A template used only for macros
d) A template that cannot be instantiated
Correct Answer: a) A template that takes another template as an argument
Explanation:
A template template parameter allows a template to accept another class template as its argument, enabling higher-order generic programming.

29. What does 'if constexpr' do?

a) Evaluates a condition at runtime
b) Evaluates a condition at compile time and discards the false branch
c) Creates a constant variable
d) Throws an error if the condition is false
Correct Answer: b) Evaluates a condition at compile time and discards the false branch
Explanation:
'if constexpr' evaluates the condition during compilation. The branch that evaluates to false is discarded and not instantiated, preventing compilation errors in that branch.

30. How does 'if constexpr' differ from a regular 'if' statement?

a) It is faster at runtime
b) Both branches of a regular 'if' must be valid, but the false branch of 'if constexpr' is discarded
c) 'if constexpr' can only be used with integers
d) There is no difference
Correct Answer: b) Both branches of a regular 'if' must be valid, but the false branch of 'if constexpr' is discarded
Explanation:
In a regular 'if', both branches must compile even if only one is executed. With 'if constexpr', the discarded branch is not instantiated, allowing invalid code for the specific type in that branch.

31. What are C++20 Concepts?

a) A way to hide template implementations
b) Named sets of requirements for template arguments
c) A new type of class
d) A method for runtime polymorphism
Correct Answer: b) Named sets of requirements for template arguments
Explanation:
Concepts allow you to specify constraints on template arguments, improving error messages and controlling overload resolution based on the properties of the types.

32. Which keyword is used to define a concept in C++20?

a) concept
b) constraint
c) requirement
d) template_concept
Correct Answer: a) concept
Explanation:
The 'concept' keyword is used to define a named boolean template expression that specifies constraints on template arguments.

33. What is a 'requires' expression?

a) An expression that allocates memory
b) An expression that checks if certain operations on types are valid
c) An expression that throws an exception
d) An expression that defines a concept
Correct Answer: b) An expression that checks if certain operations on types are valid
Explanation:
A 'requires' expression is a compile-time check that evaluates to true if the specified expressions and type requirements are valid for the given types.

34. What is an abbreviated function template?

a) A function template with a shorter name
b) A function that uses 'auto' in its parameter list to implicitly become a template
c) A function template that cannot be overloaded
d) A function template with no return type
Correct Answer: b) A function that uses 'auto' in its parameter list to implicitly become a template
Explanation:
Using 'auto' in a function parameter list (e.g., void func(auto x)) is syntactic sugar that implicitly makes the function a template with a deduced type parameter.

35. How do you create an abbreviated function template?

a) By using the 'short' keyword
b) By using 'auto' or a concept name in the parameter list
c) By omitting the return type
d) By using the 'abbrev' keyword
Correct Answer: b) By using 'auto' or a concept name in the parameter list
Explanation:
Placing 'auto' or a concept name directly in the function parameter list creates an abbreviated function template without needing the explicit 'template' syntax.

36. What is CRTP?

a) Curiously Recurring Template Pattern
b) Constant Reference Template Parameter
c) Class Recursive Template Protocol
d) Compile-time Runtime Template Pattern
Correct Answer: a) Curiously Recurring Template Pattern
Explanation:
CRTP is an idiom where a class derives from a template instantiation using itself as the template argument.

37. What is the main advantage of CRTP?

a) It enables dynamic polymorphism
b) It enables static polymorphism without virtual function overhead
c) It reduces compilation time
d) It allows runtime type checking
Correct Answer: b) It enables static polymorphism without virtual function overhead
Explanation:
CRTP allows base classes to call derived class methods at compile time, achieving polymorphic behavior without the runtime cost of virtual functions.

38. What are type traits in C++?

a) Runtime functions to check variable types
b) Compile-time templates that provide information about types
c) Macros for defining new types
d) Classes that store type metadata
Correct Answer: b) Compile-time templates that provide information about types
Explanation:
Type traits are a collection of templates in the standard library that evaluate properties of types at compile time, returning boolean values or modified types.

39. Which header file contains most standard type traits?

a) <type_traits>
b) <typeinfo>
c) <traits>
d) <memory>
Correct Answer: a) <type_traits>
Explanation:
The header contains the standard library's collection of compile-time type traits and type transformation templates.

40. What does std::is_same<T, U>::value evaluate to if T and U are the same type?

a) true
b) false
c) 1 only if they are primitive types
d) 0
Correct Answer: a) true
Explanation:
std::is_same::value is a compile-time constant that evaluates to true if T and U are exactly the same type, and false otherwise.

41. What is a template alias?

a) A macro that replaces a template
b) A new name for an existing template or a partially specialized template
c) A template that cannot be instantiated
d) A function that returns a template
Correct Answer: b) A new name for an existing template or a partially specialized template
Explanation:
A template alias (created with 'using' or 'typedef') provides a shorthand or alternative name for a template, and unlike typedefs, 'using' can be used to create alias templates.

42. Which keyword is preferred for creating a template alias?

a) typedef
b) using
c) alias
d) define
Correct Answer: b) using
Explanation:
The 'using' keyword is preferred because it can be used to create alias templates (templates that are aliases), whereas 'typedef' cannot be templated.

43. What are variable templates introduced in C++14?

a) Templates that define variables whose type depends on template parameters
b) Variables that can change their type at runtime
c) Templates for dynamic memory allocation
d) Variables that store template definitions
Correct Answer: a) Templates that define variables whose type depends on template parameters
Explanation:
Variable templates allow you to define a variable that is parameterized by a type or value, such as 'template constexpr T pi = 3.14...'.

44. Can function templates have default template arguments?

a) No, never
b) Yes, since C++11
c) Yes, but only for class templates
d) Yes, but only if they return void
Correct Answer: b) Yes, since C++11
Explanation:
Prior to C++11, only class templates could have default arguments. C++11 extended this feature to function templates as well.

45. What is the rule for default template arguments in a template parameter list?

a) They must be at the beginning
b) They must be in the middle
c) All parameters following a default argument must also have default arguments
d) There can be only one default argument
Correct Answer: c) All parameters following a default argument must also have default arguments
Explanation:
Similar to default function arguments, once a template parameter has a default value, all subsequent template parameters must also have default values.

46. Can a template member function be declared 'virtual'?

a) Yes
b) No
c) Yes, if it is a static member
d) Yes, if the class is not a template
Correct Answer: b) No
Explanation:
Virtual member functions cannot be templates. The virtual function table (vtable) must have a fixed size and layout at compile time, which is incompatible with templates.

47. Why can't template member functions be virtual?

a) Because templates are evaluated at runtime
b) Because the compiler cannot determine the exact type to put in the vtable at compile time
c) Because virtual functions are deprecated
d) Because templates do not support inheritance
Correct Answer: b) Because the compiler cannot determine the exact type to put in the vtable at compile time
Explanation:
The vtable requires a fixed number of entries determined at compile time. Since a template member function can be instantiated with infinitely many types, the vtable size would be unbounded.

48. What is the purpose of std::enable_if?

a) To enable dynamic memory allocation
b) To conditionally include or exclude a function or class from overload resolution based on a compile-time condition
c) To enable virtual functions in templates
d) To enable runtime type checking
Correct Answer: b) To conditionally include or exclude a function or class from overload resolution based on a compile-time condition
Explanation:
std::enable_if is used in SFINAE to enable a template specialization only if a specific boolean condition is true, otherwise the specialization is discarded.

49. What happens if a std::enable_if condition evaluates to false?

a) A compilation error is thrown
b) The function or class is removed from the set of candidates for overload resolution
c) The function returns null
d) The program crashes at runtime
Correct Answer: b) The function or class is removed from the set of candidates for overload resolution
Explanation:
If the condition is false, std::enable_if does not define a nested 'type', causing a substitution failure. Due to SFINAE, this is not an error but simply removes the candidate.

50. What is the difference between 'typename T::type' and 'T::type' inside a template?

a) There is no difference
b) 'typename T::type' tells the compiler it is a type, while 'T::type' is assumed to be a static member
c) 'T::type' is faster
d) 'typename T::type' is used for variables
Correct Answer: b) 'typename T::type' tells the compiler it is a type, while 'T::type' is assumed to be a static member
Explanation:
Because T is a dependent type, the compiler doesn't know if T::type is a type or a static member variable. The 'typename' keyword explicitly tells the compiler to treat it as a type.
← Previous: C++ Inheritance and Polymorphism - MCQs
Next →: C++ Variables & Data Types MCQs
New
No Image

400+ C++ Interview Questions MCQ

1. What is the primary purpose of templates in C++? a) To execute code at runtime b) To write generic,…

By MCQs Generator
NewLatest C++ Basics MCQs

Latest C++ Basics MCQs

Created by Bjarne Stroustrup as an extension of the C programming language, C++ is a powerful, high-performance, statically typed language…

By MCQs Generator
NewC++ Classes and Objects - MCQs

C++ Classes and Objects - MCQs

In C++, a class is a fundamental building block of Object-Oriented Programming (OOP) that acts as a user-defined blueprint for…

By MCQs Generator