Use a class as type specifier before it is defined

Viewed 68

So I am having trouble with the way classes are being used in std::variant.

Say I have the folowing code:

// abc.h
#include <variant>

class A
{
public:
    A(std::variant<B, C> data);
};

class B
{
public:
    B(std::variant<A, C> data);
};

class C
{
public:
    A(std::variant<A, B> data);
};

It would give me errors like error C2065: 'NameOfClass': undeclared identifier when I try to use classes that haven't been declared yet. What would be a good solution for this? In my actual project there are quite a number of classes that use each other in variants.

1 Answers

To create a variant<A, B, C>, all three classes A, B, and C must be complete - since otherwise the compiler can't figure out how big the variant has to be.

On the other hand, you should be able to declare them; but when the time comes to actually use a VAR, they must all be complete.

class A;
class B;
class C;
using VAR = std::variant<A, B, C>; // a declaration

class A {int a;};
class B {long b;};
class C {double c;};

VAR v; // a definition.
Related