Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Templates C++ Files C++ Exceptions C++ Date

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Iterators C++ Algorithms

C++ How To

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime> C++ <vector> C++ <algorithm>

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Syllabus C++ Study Plan C++ Certificate


C++ Templates


C++ Templates

Templates let you write a function or class that works with different data types.

They help avoid repeating code and make programs more flexible.


C++ Function Templates

You can create a function template by using the template keyword:

Syntax

template <typename T>
return_type function_name(T parameter) {
  // code
}
  • T is a placeholder for a data type (like int, float, etc.).
  • You can use any name instead of T, but T is common.

Example

template <typename T>
T add(T a, T b) {
  return a + b;
}

int main() {
  cout << add<int>(5, 3) << "\n";
  cout << add<double>(2.5, 1.5) << "\n";
  return 0;
}
Try it Yourself »

In the example above, add<int>(5, 3) tells the compiler to use int for T, while add<double>(2.5, 1.5) tells it to use double.


C++ Class Templates

You can also use templates to make classes that work with any data type:

Syntax

template <typename T>
class ClassName {
  // members and methods using T
};

The example below defines a template class Box that can store and display a value of any data type, and then creates one box for an int and one for a string:

Example

template <typename T>
class Box {
  public:
    T value;
    Box(T v) {
      value = v;
    }
    void show() {
      cout << "Value: " << value << "\n";
    }
};

int main() {
  Box<int> intBox(50);
  Box<string> strBox("Hello");

  intBox.show();
  strBox.show();
  return 0;
}
Try it Yourself »

And this example defines a template class Pair that stores two values of different types and displays them, then creates one pair for a person's name and age, and another for an ID and score:

Example

template <typename T1, typename T2>
class Pair {
  public:
    T1 first;
    T2 second;

    Pair(T1 a, T2 b) {
      first = a;
      second = b;
    }

    void display() {
      cout << "First: " << first << ", Second: " << second << "\n";
    }
};

int main() {
  Pair<string, int> person("John", 30);
  Pair<int, double> score(51, 9.5);

  person.display();
  score.display();

  return 0;
}
Try it Yourself »

Why Use Templates?

Templates let you:

  • Avoid repeating the same logic for different types
  • Write cleaner, reusable code
  • Support generic programming

Note: Templates must be defined in the same file where they are used (usually in the .h file).


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

OSZAR »