模板類繼承後找不到父類函式的問題

2021-09-08 20:00:48 字數 1508 閱讀 5781

錯誤示例:

1 template class

list

2 7};

89 template class special_list: public list10

15};

1617

18int main(int argc, char *ar**)

19

使用g++編譯,出現如下錯誤:

1 template_eg.cpp: in instantiation of '

void special_list::do_other_stuff(t*) [with t = int]':

2 template_eg.cpp:27:35: required from

here

3 template_eg.cpp:18:25: error: '

next

' was not declared in

this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]

4 template_eg.cpp:18:25: note: declarations in dependent base

'list

'are not found by unqualified lookup

5 template_eg.cpp:18:25: note: use '

this->next

' instead

解決方法:

1、

this->next(item)

2、

list::next(item)

3、

1 template class special_list: public list2

8 };

具體原因:

模板的處理過程分為兩步(標準編譯,vs是另一種方式)。第一步,在型別例項化前,所有不依賴於模板引數的資料被查詢和檢查。第二部,型別確定,而後處理剩餘的部分。

現在,在第一階段,沒有跡象表明next函式是依賴於模板引數的,因此它需要再型別例化前被處理。但是基型別是被當前模板例化的,且並不知道型別t會被例化成怎樣的類,編譯器無法進入基類中查詢。

而this->next則將next加入了依賴模板的函式名單,這使得編譯器會在第二階段才查詢next函式的實現,這時t是已知型別,基類list也是已知的,編譯器可以進入查詢。

在處理的第二階段,查詢表只會查詢引數依賴表中的函式並新增進表中。如果next函式是乙個與t有關的namespace中,那麼它會被查詢新增,而如果它僅是基類的乙個成員函式,那麼它對於adl是不可見的。對於next函式,編譯器需要在查詢表中檢索next,而對於this->next,編譯器查詢的是this(在第二階段模板型別例化後),之後才會查詢next。

adl(引數依賴查詢,argument-dependent lookup):

子類繼承父類,必須宣告父類的建構函式

class entity def init self,object type print parent class init called self.object type object type def get context length self raise exception get con...

模板類的繼承

模板類的繼承包括四種 1.普通類繼承模板類 cpp view plain copy template class tbase class derived public tbase 2.模板類繼承了普通類 非常常見 cpp view plain copy class tbase template cl...

模板類的繼承

模板類的繼承包括四種 1.普通類繼承模板類 cpp view plain copy template class t class tbase class derived public tbase int 2.模板類繼承了普通類 非常常見 cpp view plain copy class tbase...