C++ | Templates | Question 2

Predict the output?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
template <typename T>
void fun(const T&x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count << endl;
    ++count;
    return;
}
  
int main()
{
    fun<int> (1); 
    cout << endl;
    fun<int>(1); 
    cout << endl;
    fun<double>(1.1);
    cout << endl;
    return 0;
}

chevron_right


(A)

x = 1 count = 0

x = 1 count = 1

x = 1.1 count = 0

(B)

x = 1 count = 0

x = 1 count = 0

x = 1.1 count = 0

(C)

x = 1 count = 0

x = 1 count = 1

x = 1.1 count = 2

(D) Compiler Error


Answer: (A)

Explanation: Compiler creates a new instance of a template function for every data type. So compiler creates two functions in the above example, one for int and other for double. Every instance has its own copy of static variable. The int instance of function is called twice, so count is incremented for the second call.

Quiz of this Question

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.