問題描述
我試圖在我的項目中使用來自子類的 typedef,我已經在下面的示例中隔離了我的問題.
I'm trying to use a typedef from a subclass in my project, I've isolated my problem in the example below.
有人知道我哪里出錯了嗎?
Does anyone know where I'm going wrong?
template<typename Subclass>
class A {
public:
//Why doesn't it like this?
void action(typename Subclass::mytype var) {
(static_cast<Subclass*>(this))->do_action(var);
}
};
class B : public A<B> {
public:
typedef int mytype;
B() {}
void do_action(mytype var) {
// Do stuff
}
};
int main(int argc, char** argv) {
B myInstance;
return 0;
}
這是我得到的輸出:
sean@SEAN-PC:~/Documents/LucadeStudios/experiments$ g++ -o test test.cpp
test.cpp: In instantiation of ‘A<B>’:
test.cpp:10: instantiated from here
test.cpp:5: error: invalid use of incomplete type ‘class B’
test.cpp:10: error: forward declaration of ‘class B’
推薦答案
原因是在實例化類模板時,其成員函數的所有聲明(而不是定義)也被實例化.當需要專門化的完整定義時,類模板被精確地實例化.例如,當它用作基類時就是這種情況,就像您的情況一樣.
The reason is that when instantiating a class template, all its declarations (not the definitions) of its member functions are instantiated too. The class template is instantiated precisely when the full definition of a specialization is required. That is the case when it is used as a base class for example, as in your case.
那么發生的事情是 A
在
So what happens is that A<B>
is instantiated at
class B : public A<B>
此時 B
還不是一個完整的類型(它在類定義的右大括號之后).但是A<B>::action
的聲明要求B
是完整的,因為是在它的范圍內爬行:
at which point B
is not a complete type yet (it is after the closing brace of the class definition). However, A<B>::action
's declaration requires B
to be complete, because it is crawling in the scope of it:
Subclass::mytype
您需要做的是將實例化延遲到 B
完成的某個點.一種方法是修改 action
的聲明,使其成為成員模板.
What you need to do is delaying the instantiation to some point at which B
is complete. One way of doing this is to modify the declaration of action
to make it a member template.
template<typename T>
void action(T var) {
(static_cast<Subclass*>(this))->do_action(var);
}
它仍然是類型安全的,因為如果 var
不是正確的類型,將 var
傳遞給 do_action
將會失敗.
It is still type-safe because if var
is not of the right type, passing var
to do_action
will fail.
這篇關于不完整類型的無效使用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!