为什么编译器不让我向前声明类型定义?

假设这是不可能的,那么保持我的包含树小的最佳实践是什么?


当前回答

因为要声明一个类型,就需要知道它的大小。可以前向声明指向该类型的指针,也可以对指向该类型的指针进行类型定义。

如果您真的想这样做,您可以使用pimpl习语来减少包含。但是如果你想使用类型,而不是指针,编译器必须知道它的大小。

Edit: j_random_hacker为这个答案添加了一个重要的限定条件,基本上是需要知道该类型的大小才能使用该类型,但是如果我们只需要知道该类型的存在,就可以进行前向声明,以便创建指向该类型的指针或引用。由于OP没有显示代码,但抱怨它不会编译,我假设(可能是正确的)OP试图使用类型,而不仅仅是引用它。

其他回答

只有当您不打算使用类型本身(在此文件的作用域内),而是使用指向它的指针或引用时,才可以使用前向声明而不是完整的#includes。

要使用类型本身,编译器必须知道它的大小——因此必须看到它的完整声明——因此需要一个完整的#include。

然而,不管被指针的大小如何,编译器都知道指针或引用的大小,因此前向声明就足够了——它声明了一个类型标识符名称。

有趣的是,当使用指向类或结构类型的指针或引用时,编译器可以处理不完整的类型,从而节省了转发声明被指针类型的需要:

// header.h

// Look Ma! No forward declarations!
typedef class A* APtr; // class A is an incomplete type - no fwd. decl. anywhere
typedef class A& ARef;

typedef struct B* BPtr; // struct B is an incomplete type - no fwd. decl. anywhere
typedef struct B& BRef;

// Using the name without the class/struct specifier requires fwd. decl. the type itself.    
class C;         // fwd. decl. type
typedef C* CPtr; // no class/struct specifier 
typedef C& CRef; // no class/struct specifier 

struct D;        // fwd. decl. type
typedef D* DPtr; // no class/struct specifier 
typedef D& DRef; // no class/struct specifier 

要“fwd声明一个类型定义”,你需要fwd声明一个类或结构,然后你可以typedef声明类型。编译器可以接受多个相同的类型。

长形式:

class MyClass;
typedef MyClass myclass_t;

简式:

typedef class MyClass myclass_t;

我用继承和构造函数继承(?)替换了typedef(用来指定)。

原始

using CallStack = std::array<StackFrame, MAX_CALLSTACK_DEPTH>;

取代

struct CallStack // Not a typedef to allow forward declaration.
  : public std::array<StackFrame, MAX_CALLSTACK_DEPTH>
{
  typedef std::array<StackFrame, MAX_CALLSTACK_DEPTH> Base;
  using Base::Base;
};

通过这种方式,我可以向前声明CallStack:

class CallStack;

你可以使用正向类型定义。但是要做

typedef A B;

你必须先向前申报A:

class A;

typedef A B;

另一个解决方案是将forward声明和typedefs放在一个单独的头文件中,并包括:

// ForwardDeclarations.h
#pragma once
namespace Foo
{
    struct Bar;
    typedef Bar Baz;
}

// SomeFile.h
#include "ForwardDeclarations.h"
Foo::Baz baz;

当然,这实际上并没有减少要包含的文件数量,编译器仍然必须从磁盘读取这个文件,但至少内容比完整的定义更简单。您可以在同一个文件中添加更多的前向声明,并将其包含在相关位置。