使用模板的类的向前声明 [英] forward declaration of class using templates
问题描述
我可以为模板类使用向前声明吗?
我尝试:
Can I use forward declaration for template class?
I try:
template<class que_type>
class que;
int main(){
que<int> mydeque;
return 0;
}
template<class que_type>
class que {};
我得到:
error: aggregate 'que<int> mydeque' has incomplete type and cannot be defined.
推荐答案
类的转发声明应具有指定的完整参数列表。这将使编译器知道它的类型。
Forward declaration of a class should have complete arguments list specified. This would enable the compiler to know it's type.
当一个类型是向前声明,所有编译器知道类型是它存在;它不知道它的大小,成员或方法,因此它被称为不完全类型。因此,你不能使用类型声明一个成员或一个基类,因为编译器需要知道类型的布局。
When a type is forward declared, all the compiler knows about the type is that it exists; it knows nothing about its size, members, or methods and hence it is called an Incomplete type. Therefore, you cannot use the type to declare a member, or a base class, since the compiler would need to know the layout of the type.
你可以:
1。声明成员指针或对不完整类型的引用。
2. 声明接受/返回不完整类型的函数或方法。
3.定义接受/返回指向不完整类型的指针/引用的函数或方法。
1. Declare a member pointer or a reference to the incomplete type.
2. Declare functions or methods which accepts/return incomplete types.
3. Define functions or methods which accepts/return pointers/references to the incomplete type.
注意,在上述所有情况下,编译器不需要知道类型的确切布局&因此编译可以通过。
Note that, In all the above cases, the compiler does not need to know the exact layout of the type & hence compilation can be passed.
1的示例:
class YourClass;
class MyClass
{
YourClass *IncompletePtr;
YourClass &IncompleteRef;
};
这篇关于使用模板的类的向前声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!