簡體   English   中英

在調用傳遞給模板函數的函數時調用指針成員函數

[英]Calling pointer-to-member function in call for a function passed to a template function

這是我嘗試使用的提供的功能模板:

template <class Process, class BTNode>
void postorder(Process f, BTNode* node_ptr)
{
   if (node_ptr != 0)
   {
      postorder( f, node_ptr->left() );
      postorder( f, node_ptr->right() );
      f( node_ptr->data() );
   }
}

這是我的電話,也是我要傳遞的功能:

void city_db::print_bst() {
   postorder(&city_db::print, head);
}

void city_db::print(city_record target)
{
   std::cout << target.get_code();
}

這是我得到的編譯時(G ++)錯誤:

CityDb.cpp:85:從此處實例化

BinTree.template:80:錯誤:必須使用'。 '或'-> '以調用'f(...)'中的指針到成員函數

make:*** [CityDb.o]錯誤1

這是參考f( node_ptr->data() ); 在功能模板中。

這是針對數據結構項目的。 分配已修改,因此我們不需要將函數傳遞給函數,但是我對此已經感興趣了一段時間了,我覺得自己幾乎已經在這里了。 我已經用盡了Google和Lab TA的功能,所以如果StackOverflow有想法,將不勝感激。

您的問題是,后訂單接受必須以這種方式調用的函數對象:

f(arg);

您正在傳遞一個指向成員函數的指針。 您應該首先調用mem_fun以從指向成員的指針創建一個函數對象:

std::mem_fun(&city_db::print)

返回的函數對象帶有兩個參數:指向city_db的指針(隱式this指針)和要打印的對象。 您可以使用bind1st將第一個綁定到此,如下所示:

std::bind1st(std::mem_fun(&city_db::print), this)

現在,您應該可以對其調用后期處理了:

postorder(std::bind1st(std::mem_fun(&city_db::print), this), head);

您需要一個city_db實例來調用print on。

您傳遞的是指向成員函數的指針(將其視為vtable中的插槽),但是您也需要this指針。 您可以將此作為另一個參數傳遞給postorder函數。

template <class Object, class Process, class BTNode>
void postorder(Object* obj, Process f, BTNode* node_ptr)
{
   if (node_ptr != 0)
   {
      postorder(obj, f, node_ptr->left() );
      postorder(obj, f, node_ptr->right() );
      ((obj)->*(f))( node_ptr->data() );
   }
}

請參閱C ++常見問題精簡版

您需要將city_db :: print()設為靜態,或提供city _db對象。

如寫

void city_db::print(city_record target)
{
   std::cout << target.get_code();
}

不依賴於類狀態。 將其聲明為靜態函數,編譯器將不需要this指針來調用它。 關於該主題的常見問題解答

暫無
暫無

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

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