STL containers and abstract/derived classes

  • Thread starter =?ISO-8859-2?Q?Gordan_Kre=B9i=E6?=
  • Start date
?

=?ISO-8859-2?Q?Gordan_Kre=B9i=E6?=

I have classic interface/implementation paradigm. That does not work with
stl containers :)

Call to doAbstract(derivedList) yelds compilation error:

sample.cpp: In function 'int main(int, char**)':
sample.cpp:23: error: no matching function for call to
'doAbstract(std::list<Derived*, std::allocator<Derived*> >&)'
sample.cpp:12: note: candidates are: void doAbstract(const
std::list<Abstract*, std::allocator<Abstract*> >&)
sample.cpp:16: note: void doAbstract(const
boost::shared_ptr<Abstract>&)

For example, I've added (for me) equivalent situation with boost:shared_ptr
template that works normally.

Is this some special feature of boost:shared_ptr that std:list does not
support or I'm missing something? Is there a workaround?

#include <list>
#include <boost/shared_ptr.hpp>

class Abstract {
// whatever...
};

class Derived : public Abstract {
// whatever...
};

void doAbstract(const std::list<Abstract *> &abstractList) {
// something...
}

void doAbstract(const boost::shared_ptr<Abstract> &abstractPtr) {
// something...
}

int main(int argc, char *argv[]) {

std::list<Derived *> derivedList;
doAbstract(derivedList); // does not work?

boost::shared_ptr<Derived> derivedPtr;
doAbstract(derivedPtr); // works...

return 0;
}

// g++ (GCC) 4.1.3 20070629 (prerelease) (Debian 4.1.2-13)
// Boost 1.33.1
 
F

Frank Birbacher

Hi!
void doAbstract(const std::list<Abstract *> &abstractList) {
// something...
}

void doAbstract(const boost::shared_ptr<Abstract> &abstractPtr) {
// something...
}

int main(int argc, char *argv[]) {

std::list<Derived *> derivedList;
doAbstract(derivedList); // does not work?

No. There is not std::list constructor (which is needed here) to convert
a list said:
boost::shared_ptr<Derived> derivedPtr;
doAbstract(derivedPtr); // works...

Yes. shared_ptr has support for an appropriate conversion constructor.

But you can do:

void doAbstractOnce(Abstract* abstract) { ... }

std::list<Derived*> list;
std::for_each(
list.begin(), list.end(),
&doAbstractOnce
);

Frank
 

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

Forum statistics

Threads
474,039
Messages
2,570,375
Members
47,020
Latest member
anuradha

Latest Threads

Top