Function template type inference doesn't work with inheritance?

M

MikhailGorbachev

I'm having a problem getting derived types to be inferred as valid
parameters by a function template.

template <typename T>
struct Base {}

template<typename T>
struct Derived : public Base<T> {}

template <typename T>
void fn(Base<T>* b) { }

When I call fn with a Derived<int>* gcc gives me the error "no
matching function for call to..."
Is there any way to get the function template to accept derived
objects?

Thanks,
Alex Rubinsteyn
 
G

Gianni Mariani

I'm having a problem getting derived types to be inferred as valid
parameters by a function template.

template <typename T>
struct Base {}

template<typename T>
struct Derived : public Base<T> {}

template <typename T>
void fn(Base<T>* b) { }

// strictly not want you want but might do
template <typename X>
void fn(X* x)
{
Base<T>* b( x );
....
}

Or add this method - at least you know that it's only the derived ones
that you're getting

template <typename T>
void fn(Derived<T>* x)
{
Base<T> * b = x;
fn( b );
}


Or - hack but does the job - breaks some non-compliant compilers

// strictly not want you want but might do
template <typename X>
void fn(X* x, Convertible<X *, Base<T> *>::type = 0 )
{
Base<T>* b( x );
fn(b);
}

where Convertible is a special template class to determine if the type
of X is one of the types you allow be used - it's probably overkill
for this case.
 
Z

Zeppe

> I'm having a problem getting derived types to be inferred as valid
> parameters by a function template.
>
> template <typename T>
> struct Base {}
>
> template<typename T>
> struct Derived : public Base<T> {}
>
> template <typename T>
> void fn(Base<T>* b) { }
>
> When I call fn with a Derived<int>* gcc gives me the error "no
> matching function for call to..."
> Is there any way to get the function template to accept derived
> objects?

FAQ 5.8 http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.8
If you don't post compilable code, usually we can't help.
(btw, it seems that the section 5 of the faq is by far the most quoted,
isn't it? :) )

The answer is that it should work. The following compile correctly in
both vc8 and gcc 3.4 (the ones that I have now).


template <class T>
class Base
{ };

template <class T>
class Derived
: public Base<T>
{ };

template <class T>
void foo(const Base<T>*)
{ }

int main()
{
Derived<int> d;
foo(&d);

return 0;
}



Regards,

Zeppe
 

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,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top