Templates and Static variables in C++


In this tutorial, we will be discussing a program to understand templates and static variables in C++.

In case of function and class templates, each instance of the templates has its own local copy of the variables.

Example

 Live Demo

#include <iostream>
using namespace std;
template <typename T>
void fun(const T& x){
   static int i = 10;
   cout << ++i;
   return ;
}
int main(){
   fun<int>(1); //printing 11
   cout << endl;
   fun<int>(2); //printing 12
   cout << endl;
   fun<double>(1.1); //printing 11 again
   cout << endl;
   getchar();
   return 0;
}

Output

11
12
11

Updated on: 02-Mar-2020

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements