本文介绍了完整类型(不是)需要在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近很惊讶地发现这个代码编译(至少在gcc和MSVC ++上):

  template< typename T> ; 
class A {
public:
T getT(){return T(); }
};

class B:public A< B> {};

当这不符合时:

  A类; 

class B:public A {};

class A {
public:
B getB(){return B(); }
};

对我来说,模板类可能接受一个不完整的类型作为模板参数,函数通过调用其构造函数并仍然编译返回一个。因此,在哪里完全类型是必需的(或者如果列表更短,不需要它们在哪里)?

解决方案

不需要完成类型的情况:




  • 将成员声明为指针或对不完整类型的引用。

  • 声明接受/返回不完整类型的函数。

  • 定义接受/返回指向不完整类型的指针/引用的函数。

  • 作为模板类型参数。



基本上你可以使用一个Incomplete类型,在编译器不需要的地方知道类型的内存布局。



对于允许为不完整类型的模板类型参数,标准在 14.3.1模板类型参数 p>

I was recently surprised to know that this code compiles (at least on gcc and MSVC++):

template<typename T>
class A {
public:
    T getT() { return T(); }
};

class B : public A<B> { };

When this doesn't:

class A;

class B : public A { };

class A {
public:
    B getB() { return B(); }
};

It seems weird to me that a template class could take an incomplete type as a template parameter and have a function that returned one by calling its constructor and still compile. So where exactly are complete types required (or if the list would be shorter, where are they not required)?

解决方案

Following are the scenarios where Complete types are not required:

  • Declaring a member to be a pointer or a reference to the incomplete type.
  • Declaring functions which accepts/return incomplete types.
  • Defining functions which accept/return pointers/references to the incomplete type.
  • As a template type argument.

Basically You are fine using an Incomplete type, at any place where the compiler does not need to know the memory layout of the type.

As for the template type argument being allowed to be an Incomplete type, the Standard explicitly says so in 14.3.1 Template type arguments

这篇关于完整类型(不是)需要在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 18:28