本博客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 )