Important Introduction to Programming Short Questions
Chapter: 41
Question 1:
What keyword is used to define a template in C++?
Answer:
The keyword used to define a template in C++ is template.
Chapter: 41
Question 2:
What is the purpose of the template<class T> syntax?
Answer:
The template<class T> syntax defines a template with a generic type T, allowing the function or class to operate with any data type specified when the template is instantiated.
Chapter: 41
Question 3:
How does the compiler handle function templates at compile time?
Answer:
The compiler generates specific versions of the template function for each data type used in the code, substituting the generic type with the actual data types at compile time.
Chapter: 41
Question 4:
What is the limitation of storing template definitions and declarations in separate files?
Answer:
Templates cannot be split between declaration and definition files; both must be in the same file because the compiler needs the full definition to generate the correct code for each template instantiation.
Chapter: 41
Question 5:
Give an example of a template function for swapping two values.
Answer:
template<class T> void swap(T &x, T &y) { T tmp; tmp = x; x = y; y = tmp; }
Chapter: 41
Question 6:
What is the issue with using templates that involve different data types in the same function?
Answer:
If a template function involves different data types for its arguments, the compiler may not automatically handle type promotion or conversion, leading to compilation errors if the function cannot determine how to handle mixed types.
Chapter: 41
Question 7:
How can you force a template function to use specific data types?
Answer:
You can force a template function to use specific data types by explicitly specifying them in angle brackets, e.g., reverse<int>(a) or reverse<int, double>(a).
Chapter: 41
Question 8:
What is the role of the template<class T> keyword in defining a template class or function?
Answer:
It specifies that the class or function is a template and that T is a placeholder for a data type that will be replaced with actual types when the template is instantiated.
Chapter: 41
Question 9:
Can template functions handle multiple generic data types?
Answer:
Yes, template functions can handle multiple generic data types by defining them with more than one template parameter, e.g., template<class T, class U>.
Chapter: 41
Question 10:
Why might a function like reverse<T>(T x) fail when used with reverse<int>(a) if T is not an integer?
Answer:
It might fail because the function is designed to return a value of type T, and if T is not an integer, the function might not correctly handle type conversions or return the expected type.