Forward declaration of type defined with `using`

3.4k views Asked by At

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')

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

How to forward declare A which is defined with using?

If it is not possible, I would like to now, how to solve my problem avoiding a lot of boilerplate code.

2

There are 2 answers

3
Lightness Races in Orbit On BEST ANSWER

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

That's not relevant since you're not instantiating a boost::variant here.

Go ahead and omit the #includes.

(live demo)

Then your problem evaporates:

How to forward declare A which is defined with using?

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.

4
Paolo M On

Just replace class A; in B.hpp with using A = boost::variant<B, C, D>;

The using keyword does not forward-declare anything; 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.