使用指针与Boost :: bimap

时间:2014-04-01 17:35:41

标签: c++ boost smart-pointers

在我的应用程序中,我有以下类:

class transaction
{
public:
   .....
}

class src_transaction: public transaction
{
public:
   .....
}

class dst_transaction: public transaction
{
public:
   .....
}

我想构造一个bimap,它将采用整数和指向src_transaction或dst_transaction的指针。

如何使用Boost库做到这一点? 我应该将“类事务”声明为enable_shared_from_this吗?如果是这样,它应该是unqiue_ptr还是shared_ptr? 因为我想对src_transaction或dst_transaction中的biamp进行一些操作,如下所示:

 bimap.inset(12, "Pointer to the current transaction i.e. from the same class");

1 个答案:

答案 0 :(得分:2)

你应该尝试这样的事情:

   #include <iostream>
   #include <boost/bimap.hpp>
   #include <boost/shared_ptr.hpp>
   #include <boost/make_shared.hpp>


    using namespace std;

    class Base{

     public:
       Base(int val):_value(val){}
       int _value;

    };


    class Derv1:public Base{

      public:
         Derv1(int val):Base(val){}

    };


    class Derv2:public Base{

      public:
         Derv2(int val):Base(val){}

    };

  //typedef boost::bimap< int,Base* > bm_type;
    typedef boost::bimap< int,boost::shared_ptr<Base> > bm_type;
    bm_type bm;

    int main()
    {

    //  bm.insert(bm_type::value_type(1,new Derv1(1)));
    //  bm.insert(bm_type::value_type(2,new Derv2(2)));

     bm.insert(bm_type::value_type(1,boost::make_shared<Derv1>(1)));
     bm.insert(bm_type::value_type(2,boost::make_shared<Derv2>(2)));

      cout << "There are " << bm.size() << "relations" << endl;

      for( bm_type::const_iterator iter = bm.begin(), iend = bm.end();
          iter != iend; ++iter )
      {
        // iter->left  : data : int
        // iter->right : data : Base*

        cout << iter->left << " <--> " << iter->right->_value << endl;
      }

    }