Templated Overloaded Member Function Question

J

joseph cook

I'm confused by this output. I would expect the more specific
overloaded function to be selected:

#include <iostream>
class Base
{
};
class Derived : public Base
{};

class Foo
{
public:
template<typename U>

void bar(U* in, int a)
{
std::cout<<"Generic Call"<<std::endl;
}

void bar(Base* in, int a)
{
std::cout<<"A more appropriate choice"<<std::endl;
}
};

int main()
{
Derived *d = new Derived;

Foo foo;
foo.bar(d,1,1) // calling with derived

}

This prints "Generic Call". Is this correct? Why? I would have
expected the compiler to either pick the more specific overload, or
complain that the call was ambiguous.

What's going on ?
What's the fix ?

Thanks in advance,
 
V

Victor Bazarov

joseph said:
I'm confused by this output. I would expect the more specific
overloaded function to be selected:

#include <iostream>
class Base
{
};
class Derived : public Base
{};

class Foo
{
public:
template<typename U>

void bar(U* in, int a)
{
std::cout<<"Generic Call"<<std::endl;
}

void bar(Base* in, int a)
{
std::cout<<"A more appropriate choice"<<std::endl;
}
};

int main()
{
Derived *d = new Derived;

Foo foo;
foo.bar(d,1,1) // calling with derived

Acually, it shouldn't compile - you gave three arguments when two
are expected for *either* of 'bar' members. I suppose it's a typo.
}

This prints "Generic Call". Is this correct? Why? I would have
expected the compiler to either pick the more specific overload, or
complain that the call was ambiguous.

Why would it be ambiguous? When deducing the type for the template
'bar', 'U' is 'Derived', and it's a better match than 'Base' since
it requires no conversions.
What's going on ?

It's called "deduction of template arguments".
What's the fix ?

The fix? To do what? Try casting 'd' to 'Base*'...

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top