簡體   English   中英

在模板化類中將`std :: sort`與成員函數一起使用

[英]Using `std::sort` with a member function in a templated class

我遇到的問題是,我想在模板化類中使用帶有自定義比較功能的STL排序。

使用typedef的想法來自另一個Stackoverflow帖子

無論如何,這是代碼:

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]]); 
  }
};

我得到的錯誤是

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

先感謝您!

您正在嘗試在需要功能 指針的地方混用成員功能指針 您可以將謂詞重構為static函數,也可以使用綁定成員函數指針與類mesh的實例相關聯。

為了將實例綁定到您的成員函數指針,您需要

std::bind( mesh_instance, &mesh::compareEdgesFromIndex, _1, _2 )

如果使用C ++ 11 如果您不奢侈,則可以使用Boost中的等效功能(將boost::bind替換為std::bind boost::bind )。 C ++ 03提供了一些綁定功能,但它是有限的,我現在相信廢除的通用綁定功能可用。

您必須將compareEdgesFromIndex聲明為靜態:

static 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]]); 
}

假設compareEdges也是靜態的。 否則,您將具有成員函數指針,該成員函數指針需要調用mesh指針。

另外,如果您希望將compareEdgesFromIndex用作非靜態成員函數,則可以傳遞boost::bind(this, &mesh::compareEdgesFromIndex, _1, _2)作為比較器。

成員函數不是函數,因為要運行它,還需要知道作用於哪個對象實例。 基本上, 靜態成員只是一個常規的全局函數,具有有趣的名稱並允許訪問該類的私有部分。

確實,指向非靜態成員函數的指針不是您可以簡單調用的對象,而是可以提供對象實例以獲取可以調用的對象的對象。

您可以改為傳遞std::sort一個實現::operator()(int, int)的類的對象實例 ,給定兩個索引將返回所需的結果。 不幸的是,出於我從未在C ++中理解的原因,該對象類必須是非本地類,因為不能在模板中使用本地類(它可以是在另一個類內部定義的類,而不能是在函數或方法內部定義的類)。

作為std::bind的替代方法,您可以使用lambda,我更喜歡,因為我永遠不記得std::bind的語法。

auto cmp = [&mesh_instance](unsigned lhs, unsigned rhs) {
    return mesh_instance.compareEdgesFromIndex(lhs, rhs);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM