Boost组件multi_index_container实例(续5)

本博客http://blog.csdn.net/livelylittlefish 贴 出作 者(三二一@小鱼)相关研究、学习内容所做的笔记,欢迎广大朋友指正!

 

1. 引子

 

实例 ( 4) 的基础上,能否将 container 写成模板类?

答案是肯定的。

 

2. 写成模板类应注意的问题

 

写成模板类,应该注意几个易出现的错误。

 

2.1 operator< 作为 MyIndex 类的成员函数 1

 

例如,将 operator< 作为 MyIndex 的成员函数,如下所示。

//define multiple index

typedef struct MyIndex

{

    int x;

    int y;

    int z;

 

    MyIndex (int ax = 0, int ay = 0, int az = 0): x(ax), y(ay), z(az){}

 

    bool operator<( const MyIndex& rhs )

    {

        if (x < rhs.x) return true;

        else if (x > rhs.x) return false;

        else if (y < rhs.y) return true;

        else if (y > rhs.y) return false;

        else if (z < rhs.z) return true;

        else if (z > rhs.z) return false;

        else return false;

    }

 

    void print(char* prompt) const

    {

        cout << "(" << x << ", " << y << ", " << z << ") - " << prompt << endl;

    }

}MyIndex ;

编译时会出现如下错误。

multiindexcontainer5.cpp:120:    instantiated from ‘void MyContainer::insert(Data_T*) [with MultiIndexContainer_T = boost::multi_index::multi_index_container, boost::multi_index::member, mpl_::na>, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, std::allocator >, Tag_T = MyIndexTag, Data_T = MyTest, Index_T = MyIndex]’

multiindexcontainer5.cpp:173:    instantiated from here

/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:227: error: passing ‘const MyIndex’ as ‘this’ argument of ‘bool MyIndex::operator<(const MyIndex&)’ discards qualifiers

大致意思是说,不应该将 operator<(const MyIndex&) 函数的参数声明为 const 。如果将 const 去掉,还是会出现错误,如下。

 

2.2 operator< 作为 MyIndex 类的成员函数 2

//define multiple index

typedef struct MyIndex

{

    int x;

    int y;

    int z;

 

    MyIndex (int ax = 0, int ay = 0, int az = 0): x(ax), y(ay), z(az){}

 

    bool operator<( MyIndex& rhs )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值