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: 2020-03-02T11:13:22+05:30

604 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements