使用模板前向声明类
我可以对模板类使用前向声明吗?
我尝试:
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是模板问题。除非已完全定义类型,否则不能将其用作按值变量。
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.
类的前向声明应该指定完整的参数列表。这将使编译器知道它的类型。
当类型被前向声明时,编译器只知道该类型存在;它对其大小、成员或方法一无所知,因此称为不完整类型。因此,您不能使用该类型来声明成员或基类,因为编译器需要知道该类型的布局。
您可以:
1。声明一个成员指针或对不完整类型的引用。
2. 声明接受/返回不完整类型的函数或方法。
3. 定义接受/返回不完整类型的指针/引用的函数或方法。
请注意,在上述所有情况下,编译器不需要知道类型和类型的确切布局。这样编译就可以通过了。
示例 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: