Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to declare cyclic type aliases in C++

I have a piece of code that looks something like

class Something {};
using MyUnionType = std::variant<A, B>;
using A = Something;
using B = std::vector<MyUnionType>;

but this does not compile, and I get

error: use of undeclared identifier 'A' in the declaration of MyUnionType

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and error: use of undeclared identifier 'MyUnionType' in the declaration of B.

Is there a way to declare these types (aliases) or is C++ not advanced enough to do this?

I have tried to forward-declare A and B as follows

class Something {};
class A;
class B;
using MyUnionType = std::variant<A, B>;
using A = Something;
using B = std::vector<MyUnionType>;

but this also does not compile.

error: typedef redefinition with different types ('Something' vs 'A')

error: typedef redefinition with different types ('std::vector<MyUnionType>' (aka 'vector<variant<A, B>>') vs 'B')

When I try to move the declaration of MyUnionType to the bottom and forward-declare MyUnionType instead, I get a similar error.

>Solution :

If you want to reference the class itself, you have to define a new type.

#include <variant>
#include <vector>
struct Something {};
struct MyUnionType;
using A = Something;
using B = std::vector<MyUnionType>;
struct MyUnionType {
    std::variant<A, B> v;
};

You may be interested in some references: https://en.cppreference.com/w/cpp/language/type_alias , https://en.cppreference.com/w/cpp/language/declarations .

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading