Why won't the compiler let me forward declare a typedef?
Assuming it's impossible, what's the best practice for keeping my inclusion tree small?
Why won't the compiler let me forward declare a typedef?
Assuming it's impossible, what's the best practice for keeping my inclusion tree small?
Because to declare a type, its size needs to be known. You can forward declare a pointer to the type, or typedef a pointer to the type.
If you really want to, you can use the pimpl idiom to keep the includes down. But if you want to use a type, rather than a pointer, the compiler has to know its size.
Edit: j_random_hacker adds an important qualification to this answer, basically that the size needs to be know to use the type, but a forward declaration can be made if we only need to know the type exists, in order to create pointers or references to the type. Since the OP didn't show code, but complained it wouldn't compile, I assumed (probably correctly) that the OP was trying to use the type, not just refer to it.
You can do forward typedef. But to do
typedef A B;
you must first forward declare A:
class A;
typedef A B;
In C++ (but not plain C), it's perfectly legal to typedef a type twice, so long as both definitions are completely identical:
// foo.h
struct A{};
typedef A *PA;
// bar.h
struct A; // forward declare A
typedef A *PA;
void func(PA x);
// baz.cc
#include "bar.h"
#include "foo.h"
// We've now included the definition for PA twice, but it's ok since they're the same
...
A x;
func(&x);
For those of you like me, who are looking to forward declare a C-style struct that was defined using typedef, in some c++ code, I have found a solution that goes as follows...
// a.h
typedef struct _bah {
int a;
int b;
} bah;
// b.h
struct _bah;
typedef _bah bah;
class foo {
foo(bah * b);
foo(bah b);
bah * mBah;
};
// b.cpp
#include "b.h"
#include "a.h"
foo::foo(bah * b) {
mBah = b;
}
foo::foo(bah b) {
mBah = &b;
}