views:

4705

answers:

4

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?

+11  A: 

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.

tpdi
Well, forward declarations of class types declare these types without knowledge of their size. Also, in addition to being able to define pointers and references to such incomplete types, functions can be declared (but not defined) which take parameters and/or return a value of such types.
j_random_hacker
+14  A: 

You can do forward typedef. But to do

typedef A B;

you must first forward declare A:

class A;

typedef A B;

JH
+1 in the end because while you technically can't "forward-typedef" (i.e. you can't write "typedef A;"), you can almost certainly accomplish what the OP wants to accomplish using your trick above.
j_random_hacker
+3  A: 

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);
Adam Rosenfield
+1  A: 

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;
 }
LittleJohn