views:

387

answers:

2

I'm doing some policy-based designs here and I have the need to typedef lots of template types to shorten the names.
Now the problem comes that when I need to use a pointer to one of those types I try to just forward-declare it but the compiler complains with a test.cpp:8: error: using typedef-name ‘Test1’ after ‘class’
It's nothing to do with sizes as I don't need the obj at all, its just a pointer in a ".h" file where I don't want to bring the whole template in.
This is g++:

//Works
class Test{};
class Test;

//Doesn't work
class Test{};
typedef Test Test1;
class Test1;

Any hint?

+9  A: 
Johannes Schaub - litb
Tried to upvote you because you beat me but I'm out of votes for today :(
Billy ONeal
well, the problem comes in a .cpp file that includes this seconday .h file and the original one with the typedef.I need the forward declaration because I need to declare a pointer to that class and want to avoid including the template file(with the typedef in).So there is no solution for such a thing?
Yogur
Then you have to forward-declare the class and the typedef in the file explicitly. Remember that between files typedef'd names do not exist -- the compiler expands them into their untypedefed names at compile time. If you simply forward declare the typedef'd name later then it will fail at link time because after compilation no such name should exist.
Billy ONeal
Great! Thanks for that last edit!! I think that matches my requirements.
Yogur
@BillyONeal - +1 given
RC
+1  A: 
typedef Test Test1;
class Test1;

fails because the typedef statement serves as the declaration for the Test1 type.

Basically, when the compiler sees the typedef, it remembers that Test1 is a synonym for Test. Then when it sees class Test1;, it thinks there's a new type you are declaring. But it can't treat that as a declaration because the name Test1 is already being used by the typedef.

If you want to use a forward declaration for Test1, for example, you have to put the typedef in each file using that typedef as a forward declaration. Therefore, instead of class Test1;, you'd do:

class Test;
typedef Test Test1;
Billy ONeal