Reputation: 957
While reading about templates I encountered the following code:
template<class T>
void f(T x, T y) {
cout << "template" <<endl;
}
void f(int w, int z) {
cout << "Non template" <<endl;
}
int main() {
f(1,2);
f('a','b');
f(1,'b');
}
The book states that the output for this code would be:
Non template Template Non template
The last line, f(1,'b'), is baffling me (or its output rather). What is the rule of thumb that the compiler is following in this instance? Thanks in advance.
Upvotes: 3
Views: 137
Reputation: 4763
First function :
You have a f(int,int) defined, so compiler will take that one. If you want to explicitly use the template you can call it like :
f<int>(1,2);
Second function :
Well, you don't have a f(char,char) defined, but it matches your template definition, so it uses that.
Third function :
You don't have a template for f(T1, T2) . However you have an implicit cast to int from char on a function that will take f(int,int). So it takes the function again.
Furthermore if f(int,int) wouldn't be defined, then your Template function wouldn't qualify to be called for f(int,char) since it has different types as parameters.
Upvotes: 5
Reputation: 20774
The template takes both arguments of the same type T
.
f(1,'b')
doesn't match the template because 1
and 'b'
are not of the same type.
Upvotes: 1