
Pau Garcia i Quiles skrev:
Hello,
I'm having trouble when adding elements to a ptr_map. If I use a ptr_vector instead, it works (code for ptr_map and ptr_vector follows).
* With ptr_map: ===============
#include <iostream> #include <string> #include <boost/function.hpp> #include <boost/any.hpp> #include <boost/ptr_container/ptr_map.hpp>
class Base { };
class X : public Base { public: std::string text() { std::cout<< std::string("hello world!") << std::endl; return std::string("hello world!"); } };
class Y : public Base { public: int value() { return 5; } };
class Z : public Base { public: bool isEnabled() { return true; } };
// [...] // There will be hundreds of classes like X, Y and Z, only quite more complex
class ProxyBase { public: virtual boost::any field() = 0; };
template<class T> class Proxy : public ProxyBase { typedef T result_type;
public: Proxy(T& inst, boost::function<boost::any ( T )> f) : inst_(inst), f_(f) { ; };
boost::any field() { return boost::any( f_(inst_) ); }
T& inst_; boost::function<boost::any ( T )> f_;
};
int main() {
boost::ptr_map<std::string, ProxyBase> m;
X x; Proxy<X>* px = new Proxy<X>(x, boost::mem_fn(&X::text)); std::cout << "Calling a proxy object Proxy<X> outputs: " << boost::any_cast<std::string>( px->field() ) << std::endl;
// m.insert(std::string("test"), px ); // FIXME Why does this 'insert' fail?
Please see the FAQ: http://www.boost.org/doc/libs/1_35_0/libs/ptr_container/doc/faq.html#why-doe... -Thorsten