F
Frank Neuhaus
Hi
I am trying to overload a function for several types and I have
encountered some problems.
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?
Thank you very much
I am trying to overload a function for several types and I have
encountered some problems.
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?
Thank you very much