|
Boost : |
From: John Hunter (jdhunter_at_[hidden])
Date: 1999-11-01 18:00:24
I have a piece of sample code in which I have a vector of shared
pointers (boost::shared_ptr<>). Can anyone tell me why I am unable to
iterate using the STL algorithm for_each (fail to compile; message
below) but I can manually loop over the container just fine.
e.g.
//this works
vector<Aptr>::iterator ix;
for (ix = x.begin(); ix != x.end(); ++ix)
(*ix)->print();
//this doesn't
std::for_each(x.begin(), x.end(), std::mem_fun(&Base::print));
Thanks in advace; complete code and compiler error message below.
John Hunter
Code:
#include <iostream>
#include <string>
#include <map>
#include <memory>
#include <vector>
#include <algorithm>
#include <boost/smart_ptr.hpp>
class Base {
public:
virtual ~Base() {};
virtual void print() = 0;
virtual Base* clone() const { } ;
};
class Foo : public Base {
int x;
public:
Foo() : x(0) {};
~Foo () { std::cout << "Foo: ouch" << endl; }
void print() { std::cout << "I am Foo" << endl;}
Foo* clone() const { return new Foo(*this); }
};
class Bar : public Base {
int x;
public:
Bar() : x(0) {};
~Bar () { std::cout << "Bar: ouch" << endl; }
void print() { std::cout << "I am Bar" << endl;}
Bar* clone() const { return new Bar(*this); }
};
int main() {
const Foo foo;
const Bar bar;
typedef std::map<const std::string, const Base*> Map;
Map m;
m["foo"] = &foo;
m["bar"] = &bar;
typedef boost::shared_ptr<Base> Aptr;
vector<Aptr> x;
std::string s;
std::cout << "enter foo or bar" << endl;
while (cin >> s)
x.push_back(Aptr(m[s]->clone())); //use the constructor
//this works
vector<Aptr>::iterator ix;
for (ix = x.begin(); ix != x.end(); ++ix)
(*ix)->print();
//this doesn't
std::for_each(x.begin(), x.end(), std::mem_fun(&Base::print));
}
Compiler error message:
localhost:~/c/examples> g++ test.cpp
g++ test.cpp
/usr/local/lib/gcc-lib/i586-pc-linux-gnu/2.95/../../../../include/g++-3/stl_algo.h:
In function `class mem_fun_t<void,Base> for_each<main()::Aptr *,
mem_fun_t<void,Base> >(main()::Aptr *, main()::Aptr *,
mem_fun_t<void,Base>)':
test.cpp:58: instantiated from here
/usr/local/lib/gcc-lib/i586-pc-linux-gnu/2.95/../../../../include/g++-3/stl_algo.h:83:
no match for call to `(mem_fun_t<void,Base>) (boost::shared_ptr<Base>
&)'
/usr/local/lib/gcc-lib/i586-pc-linux-gnu/2.95/../../../../include/g++-3/stl_function.h:566:
candidates are: void mem_fun_t<void,Base>::operator ()(Base *) const
localhost:~/c/examples>
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk