使用 using 定义的类型的前向声明

Forward declaration of type defined with `using`

假设我有这样的情况:

//A.hpp
#include "B.hpp"
#include "C.hpp"
#include "D.hpp"

using A = boost::variant<B, C, D>;

//B.hpp
#include <memory>

class A;
using AA = std::unique_ptr<A>;

这给我以下错误:error: typedef redefinition with different types ('boost::variant<B, C, D>' vs 'A')

我不能在 A.hpp 中省略 #include,因为 boost::variant 需要完整的类型。

如何转发声明用using定义的A

如果不可能,我现在想知道如何解决我的问题,避免大量样板代码。

只需将 B.hpp 中的 class A; 替换为 using A = boost::variant<B, C, D>;

using关键字不转发声明任何东西;它只是声明一个类型别名。因此,当在 "A.hpp" 中包含 "B.hpp" 时,您将一个名为 A 的 class 的前向声明和一个名为 A 的类型别名的声明放入同一个翻译单元中。

I can't omit #include's in A.hpp because boost::variant wants complete types.

这不相关,因为您没有在此处实例化 boost::variant

继续并省略 #includes。

(live demo)

那么你的问题就烟消云散了:

How to forward declare A which is defined with using?

不要。再次使用 using 或者,更好的是,将 using 语句提升到它自己的 header 中,然后可以将其包含在任何需要的地方。