Re: Function overloading
Frank Neuhaus wrote:
I am trying to overload a function for several types and I have
encountered some problems.
You basically have overloaded your function for an *infinite* set of
types since you mixed in a template. Not *several*, but *way too many*.
Below is the program I am considering:
#include <iostream>
#include <string>
struct Base {};
class Derived : public Base {};
class SomeClass {};
void f(int t)
{
std::cout << "int" << std::endl;
}
void f(const Base* t)
{
std::cout << "base" << std::endl;
}
template<typename T>
void f(const T& t)
{
std::cout << "cref" << std::endl;
};
template<>
void f(const std::string& t)
{
std::cout << "string" << std::endl;
};
int main()
{
f(5); // expecting "int"
Base b;
f(&b); // expecting "base"
Derived d;
f(&d); // expecting "base"
SomeClass c;
f(c); // expecting "cref"
std::string test="test";
f(test); // expecting "string"
};
I want the call f(&b) and f(&d) to result in the output "base". What I
am getting is the result "cref" for both calls. The compiler appears
to prefer making T=Base*, and T=Derived* respectively in the template
function. What do I need to change in order to make this result in the
desired output? What exactly are the internal rules of the compiler
for function overloading - i.e in which cases does it prefer which of
the overloads?
The rules are complex. There is no way I can explain them all in a
single newsgroup posting (I'm just too lazy). Find a book and study.
Or get the Standard and read chapter 13. However, in your case I can
tell you this... Since you added a template, it is considered in the
resolution. The template argument for that function template is deduced
from the argument you supplied. Try printing out the type you get:
template<typename T>
void f(const T& t)
{
std::cout << "f<T>, T == " << typeid(T).name() << std::endl;
};
What happens here is that the match is closer and the rank of the
conversion (if any) is higher than the conversion of 'Derived*' to
'Base*' and then to 'Base const*', I'm guessing. The determination of
the rank is done according to some table in the chapter 13, and you can
probably find it in a decent book that talks about overload resolution.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask