0

I have two C++ classes/structs which use each other's type alias, but the compiler doesn't recognize one of the type aliases.

In "A.h":

#pragma once

#include "B.h"

struct A {
    using id_t = int;
    B::id_t id;
};

And in "B.h":

#pragma once

#include "A.h"

struct B {
    using id_t = int;
    A::id_t id;
};

In "main.cpp":

#include "A.h"
#include "B.h"

int main(int argc, char const *argv[])
{
    A a;
    return 0;
}

When I compiled the code, I got an error message as

In file included from ../A.h:3,
                 from ../main.cc:1:
../B.h:7:5: error: ‘A’ does not name a type
    7 |     A::id_t id;
      |     ^

I know that C++ forbids classes containing a member field of each other, which causes an "infinite loop", but why isn't it allowed to use each other's type alias?

Using forward declaration also seems infeasible, because the classes must know each other's "complete" definition.

Clyx
  • 43
  • 7
  • A C++ compiler works top to bottom through your code. You can only use things which are declared prior to the point where they are used. Either the compiler sees the definition of `A` first or the definition of `B` first. If it sees `A` first, then `B::id_t` hasn't been declared yet and the other way around. You can't avoid that issue. – user17732522 Mar 04 '23 at 20:09
  • What you are facing is a design mistake. You have designed class A such that it can't have a definition until class B has been defined. And you have designed class B such that it can't have a definition until class A has been defined. This is solved by taking a different design approach. – Drew Dormann Mar 04 '23 at 20:24

0 Answers0