简体   繁体   English

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

[英]Forward declaration of type defined with `using`

Let's assume I have such situation: 假设我有这种情况:

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

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

I can't omit #include 's in A.hpp because boost::variant wants complete types. 我不能在A.hpp省略#include ,因为boost::variant完整的类型。

How to forward declare A which is defined with using ? 如何转发声明using定义的A

If it is not possible, I would like to now, how to solve my problem avoiding a lot of boilerplate code. 如果不可能,我现在想如何避免大量的样板代码来解决我的问题。

I can't omit #include 's in A.hpp because boost::variant wants complete types. 我不能在A.hpp省略#include ,因为boost::variant完整的类型。

That's not relevant since you're not instantiating a boost::variant here. 这无关紧要,因为您没有在此处实例化boost::variant

Go ahead and omit the #include s. 继续并省略#include

( live demo ) 现场演示

Then your problem evaporates: 然后您的问题消失了:

How to forward declare A which is defined with using? 如何转发声明使用定义的A?

Don't. 别。 Use using again or, better yet, hoist the using statement into its own header that may then be included wherever it's needed. 再次使用using ,或者更好的是,将using语句提升到其自己的标头中,然后可以在需要的地方包含它。

Just replace class A; 只需替换class A; in B.hpp with using A = boost::variant<B, C, D>; 在B.hpp中using A = boost::variant<B, C, D>;

The using keyword does not forward-declare anything; using关键字不转发任何声明; it just declares a type-alias. 它只是声明了类型别名。 So, when in "A.hpp" you include "B.hpp", you put into the same translation unit both a forward declaration of a class named A, and the declaration of a type alias named A. 因此,当在“ A.hpp”中包含“ B.hpp”时,将同一个转换类(称为A的类的向前声明)和类型别名(称为A)的声明放入同一个转换单元中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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