将`std :: sort`与模板化类中的成员函数一起使用

Yuu*_*uta 1 c++ templates typedef function-pointers class

我遇到的问题是我想在模板化的类中使用STL的自定义比较函数.

使用typedef的想法来自另一个Stackoverflow Post

无论如何,这是代码:

template <typename R,typename S>
class mesh{
  /* some stuff */

  void sortData(){
    typedef bool (*comparer_t)(const S,const S);
    comparer_t cmp = &mesh::compareEdgesFromIndex;
    sort(indx,indx+sides*eSize,cmp);
  }

  /* more stuff */

  // eData and cIndx are member variables
  bool compareEdgesFromIndex(const S a,const S b){
    return compareEdges(eData[cIndx[2*a]],eData[cIndx[2*a+1]],eData[cIndx[2*b]],eData[cIndx[2*b+1]]); 
  }
};
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

mesh.h:130:29: error: cannot convert ‘bool (mesh<float, unsigned int>::*)(unsigned int, unsigned int)’ to ‘comparer_t {aka\
bool (*)(unsigned int, unsigned int)}’ in initialization
Run Code Online (Sandbox Code Playgroud)

先感谢您!

K-b*_*llo 5

您正在尝试混合成员函数指针,其中需要一个函数指针.您可以将谓词重构为static函数,也可以使用绑定成员函数指针与类的实例相关联mesh.

为了将实例绑定到您的成员函数指针,您可以这样做

std::bind( mesh_instance, &mesh::compareEdgesFromIndex, _1, _2 )
Run Code Online (Sandbox Code Playgroud)

如果使用C++ 11.如果您没有奢侈品,那么您可以使用Boost的等效功能(替换std::bindboost::bind).C++ 03提供了一些绑定功能,但它有限,而且我认为现在已经过时了,可以使用通用绑定功能.