C ++ pass derived shared_ptr class to templated function

The first thing should work, and then something that doesn't. Why is it not a question.

I declare two classes:

class Base { ... };
class Derived : public Base { ... };


Then I have the following function:

void foo(shared_ptr<Base> base);   


The following code should work correctly?

share_ptr<Derived> derived;


Now, forget the above, I am declaring three classes:

class Foo { ... };
template <typename TYPE> class Base { ... };
class Derived : public Base<Foo> { ... };


Elsewhere I declare a templated function:

template <typename TYPE> void foo(shared_ptr<Base<TYPE> > base); 


The following code doesn't work:

shared_ptr<Derived> derived;


It says that no matching function foo (...) was found that takes share_ptr<Derived>

First, should the original example work? And second, what do you think might be a problem in the second example, when I have shared_ptr

for a class that is derived from a specialized base class.


source to share

2 answers

I don't think the compiler will go through the level of indirection in this way. Rather, you can explicitly instantiate foo with the TYPE set to Foo. For example, the following compilations via g ++:


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

template<typename T>
int foo(boost::shared_ptr<Base<T> > base) {return 0;}

boost::shared_ptr<Derived> derived;
int t = foo<Foo>(derived);

int main() {return 0;}




It might be a copy and paste error, but to cover all bases, you missed the 'd' in 'shared' for share_ptr<Derived>




All Articles