1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M11 Templates
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
11Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M11 Templates

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
11Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Templates (Generics)

Overview

If you write a function int max(int a, int b), and later need to find the maximum of two doubles, you have to write a second function using Overloading. If you need it for strings, you write a third. This is exhausting and prone to typos.

C++ introduced Templates (often called Generics in Java/C#). A Template allows you to write a single master blueprint of a function (or Class) where the exact Data Type is left completely blank (usually represented by the letter T). When you finally call the function, the C++ Compiler analyzes your data, dynamically fills in the blank, and physically generates the mathematically correct code in the background.

Syntax

cpp
#include <iostream>

// 1. THE TEMPLATE DEFINITION
// We tell the compiler: "T represents a generic, unknown data type"
template <typename T>
T getMaximum(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    // 2. EXECUTING THE TEMPLATE
    // The compiler sees we passed integers. It secretly generates an 'int' version of the function!
    std::cout << getMaximum<int>(10, 50) << "\n"; // Prints 50
    
    // The compiler sees doubles. It secretly generates a 'double' version!
    std::cout << getMaximum<double>(3.14, 2.71) << "\n"; // Prints 3.14
    
    // Modern C++ feature: The <type> can often be completely omitted!
    // The compiler just infers it based on the arguments!
    std::cout << getMaximum(100, 200) << "\n"; 
    
    return 0;
}

Common Pitfalls

  • Template Code Bloat. Templates do NOT save binary file size. If you call getMaximum with 15 different data types across your project, the compiler physically generates and compiles 15 completely separate functions in your final executable, which can balloon the .exe size significantly.
  • The Header File Trap. Unlike standard functions, you CANNOT separate a Template's Declaration (in the .h file) from its Definition (in the .cpp file). Because the compiler needs to see the full code to generate the types dynamically, the entire Template body MUST be written directly inside the header file.

Interview Questions

When does the C++ compiler actually evaluate and generate the code for a Template?

Templates are evaluated strictly at Compile-Time. The compiler scans your entire project, logs every single Data Type you used the template with, and hardcodes those specific functions into the binary before the program ever runs. This guarantees absolutely zero runtime performance overhead.

Real-World Example

Building a generic Class Template. This is the exact architectural foundation of std::vector!

example
cpp
#include <iostream>

// The Class can now hold ANY data type!
template <typename T>
class Box {
private:
    T item;
public:
    Box(T i) : item(i) {}
    T getItem() { return item; }
};

int main() {
    Box<int> intBox(99);
    Box<std::string> strBox("Hello");
    
    std::cout << intBox.getItem() << "\n";
    return 0;
}

Check Your Knowledge

Test your understanding of Templates (Generics) with these quick questions.

Question 1

Why must you generally write the entire implementation of a Template Function directly inside the `.h` header file instead of a `.cpp` file?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Templates (Generics)

Overview

If you write a function int max(int a, int b), and later need to find the maximum of two doubles, you have to write a second function using Overloading. If you need it for strings, you write a third. This is exhausting and prone to typos.

C++ introduced Templates (often called Generics in Java/C#). A Template allows you to write a single master blueprint of a function (or Class) where the exact Data Type is left completely blank (usually represented by the letter T). When you finally call the function, the C++ Compiler analyzes your data, dynamically fills in the blank, and physically generates the mathematically correct code in the background.

Syntax

cpp
#include <iostream>

// 1. THE TEMPLATE DEFINITION
// We tell the compiler: "T represents a generic, unknown data type"
template <typename T>
T getMaximum(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    // 2. EXECUTING THE TEMPLATE
    // The compiler sees we passed integers. It secretly generates an 'int' version of the function!
    std::cout << getMaximum<int>(10, 50) << "\n"; // Prints 50
    
    // The compiler sees doubles. It secretly generates a 'double' version!
    std::cout << getMaximum<double>(3.14, 2.71) << "\n"; // Prints 3.14
    
    // Modern C++ feature: The <type> can often be completely omitted!
    // The compiler just infers it based on the arguments!
    std::cout << getMaximum(100, 200) << "\n"; 
    
    return 0;
}

Common Pitfalls

  • Template Code Bloat. Templates do NOT save binary file size. If you call getMaximum with 15 different data types across your project, the compiler physically generates and compiles 15 completely separate functions in your final executable, which can balloon the .exe size significantly.
  • The Header File Trap. Unlike standard functions, you CANNOT separate a Template's Declaration (in the .h file) from its Definition (in the .cpp file). Because the compiler needs to see the full code to generate the types dynamically, the entire Template body MUST be written directly inside the header file.

Interview Questions

When does the C++ compiler actually evaluate and generate the code for a Template?

Templates are evaluated strictly at Compile-Time. The compiler scans your entire project, logs every single Data Type you used the template with, and hardcodes those specific functions into the binary before the program ever runs. This guarantees absolutely zero runtime performance overhead.

Real-World Example

Building a generic Class Template. This is the exact architectural foundation of std::vector!

example
cpp
#include <iostream>

// The Class can now hold ANY data type!
template <typename T>
class Box {
private:
    T item;
public:
    Box(T i) : item(i) {}
    T getItem() { return item; }
};

int main() {
    Box<int> intBox(99);
    Box<std::string> strBox("Hello");
    
    std::cout << intBox.getItem() << "\n";
    return 0;
}

Check Your Knowledge

Test your understanding of Templates (Generics) with these quick questions.

Question 1

Why must you generally write the entire implementation of a Template Function directly inside the `.h` header file instead of a `.cpp` file?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A