Saturday, February 16, 2008

Template, Forward Class Declaration and Typedef

Now that I'm back to the C++ wonder land, it's time to re-familiarize myself with the basic.

In C++, ideally, you should "forward declare" a class and only include its full declaration when necessary, since this would minimize the dependency relationship between files and cut down build time:

class A;
...
void foo(const A& a);

But things can quickly get problematic when there is typedef involved, for example in the previous case, if A is later typedefed as:

typedef B A;

Compiler will complaint that A is defined in two places with different type. To do this  cleanly, you need:

class B;                //forward declaration of B first
typedef B A;          //now typedef A
...
void foo(const A& a);

But what if B is a template, something like:

typedef vector<B> A;          //now typedef A

Unfortunately, I have yet find a way to make this work...