By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,657 Members | 994 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,657 IT Pros & Developers. It's quick & easy.

Templated Overloaded Member Function Question

P: n/a
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,

Mar 16 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
joseph cook wrote:
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 16 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.