forward declaration of class using templates

岁酱吖の 提交于 2019-12-24 05:36:20

问题


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 {};

I get:

error: aggregate 'que<int> mydeque' has incomplete type and cannot be defined.

回答1:


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.

You can:

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.

Example of 1:

class YourClass;
class MyClass 
{
    YourClass *IncompletePtr;
    YourClass &IncompleteRef;
};



回答2:


This is not a template issue. You cannot use a type as a by-value variable unless it has been fully defined.




回答3:


No. At the point of instantiation, the complete definition of the class template must be seen by the compiler. And its true for non-template class as well.



来源:https://stackoverflow.com/questions/7111252/forward-declaration-of-class-using-templates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!