1

I have several overloaded functions:

class A {}; class B : public A {}; template<class T> void f(T a) {} // function 1 void f(A* p) {} // function 2 

When I call

B* b; f(b); // the function 1 is called other than the 2 

I expect the version 2 is called. Why not and how to let the version 2 is called?

2 Answers 2

3

You called your function with a child class pointer. The template matches this exactly, while calling function 1 would require a conversion to base pointer. Thus the template call is a better match.

You can explicitly static_cast to the base class to force the call of the base-pointer version, or I believe you could use something like enable_if to disable the template for children of A.

Sign up to request clarification or add additional context in comments.

2 Comments

Now I understand. How to work around to let it call the version 2?
@StoryTeller Of course. This is one of the simplest and most classical cases of meta-programming.
2

The compiler selects the best overload it can see. Type deduction instantiates your template as f(B*), and that's clearly a better overload than f(A*). The usual solution for this is something like:

void f( A* p ) { } template <typename T> void doF( T a, A const* ) { f( static_cast<A*>( a ) ); } template <typename T> void doF( T a... ) { // your current template implementation } template <typename T> void f( T a ) { doF<T>( a, 42 ); } template <typename T> void f( T* a ) { doF<T*>( a, static_cast<T*>( 0 ) ); } 

The above works because for non-pointer types, the only function which can be called is the first template above, which will end up in your template implementation. For pointer types, the last template is more specialized, and so will be a better match (unless the pointer is A*, in which case, the non-template function will be called); it will pass a null pointer of type T* to doF. If T* converts implicitly to an A*, the first doF is the better match; otherwise, the first doF cannot be called, and so the second will be called.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.