mercredi 28 juin 2017

Template function - Does the template override the normal functions

I am testing the following code with c++ templates. I have written a square function using int and float and with a function template.

#include <iostream>
using namespace std;

int square (int a){
cout << "int function" << endl;
return a*a;
};

float square (float a){
cout << "float function" << endl;
return a*a;
};

template <typename T>
T square (T x){
cout << "template function" << endl;
return x*x;
}

int main(){
cout << square<int>(5) << endl;
cout << square<float>(5.5) << endl;
cout << square(5) << endl;
cout << square(5.5) << endl;
return 0;
}

The output is

template function
25
template function
30.25
int function
25
template function
30.25

though I expected

template function
25
template function
30.25
template function
25
template function
30.25

Can someone explain the difference ?

Aucun commentaire:

Enregistrer un commentaire