Lab P17 β€” Use templates.

NBC351 Β· Program 17⏱ 8 min read❓ 5 MCQs

Aim

Aim: Demonstrate function and class templates.

Theory

Demonstrate function and class templates.

C++ Program

#include 
using namespace std;
template 
T maxVal(T a,T b){ return a>b?a:b; }
template 
class Box { T v; public: Box(T x):v(x){} void show(){cout< b(5); b.show(); return 0; }

Expected Output

7
3.5
5

Explanation

  • maxVal template for int/double.
  • Box instantiation.

Viva / Important Questions

Short Questions

  1. What is template?
  2. Function vs class template?

Long Questions

  1. Explain the program in detail.
  2. Discuss key concepts demonstrated.

MCQ Practice

1. Template resolved at:

  • Compile time
  • Run time
  • Link time
  • Never
Answer: Compile time.

2. template keyword defines:

  • Generic code
  • Concrete code
  • Macro
  • None
Answer: Generic code.

3. Class template instantiated with:

  • Box
  • Box
  • template Box
  • None
Answer: Box.

4. Templates support:

  • Multiple type params
  • Only one
  • Only int
  • None
Answer: Multiple type params.

5. STL is built on:

  • Templates
  • Inheritance
  • Virtual
  • None
Answer: Templates.

Quick Revision

  • Templates = generic code.
  • Compile-time instantiation.