Boost logo

Boost Users :

From: Thorsten Ottosen (thorsten.ottosen_at_[hidden])
Date: 2008-04-14 03:25:04


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-does-ptr-map-t-insert-replace-take-two-arguments-the-key-and-the-pointer-instead-of-one-std-pair-and-why-is-the-key-passed-by-non-const-reference

-Thorsten


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net