简体   繁体   中英

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

I get:

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM