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

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");

最佳答案

您应该尝试这样的事情:

   #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;
      }

    }

关于c++ - 在Boost::bimap中使用指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22792920/

10-15 00:34
查看更多