What\'s the best solution to forward declare a typedef within a class. Here\'s an example of what I need to solve:
class A;
class B;
class A
{
typedef boos
There is no such thing as forward declaring a typedef
unfortunately. However, there's a trick using late template instantiation:
template <typename T> class BImpl;
template <typename T>
class AImpl
{
public:
typedef boost::shared_ptr<AImpl> Ptr;
typename BImpl<T>::Ptr foo();
};
template <typename T>
class BImpl
{
public:
typedef boost::shared_ptr<BImpl> Ptr;
typename AImpl<T>::Ptr bar();
};
typedef AImpl<void> A;
typedef BImpl<void> B;
This should hopefully accomplish the thing you're aiming for.
There's no way to forward declare either
typedef
So - you can't forward declare a typedef
and if you could, you still wouldn't be able to do that, because you'd need to do this:
class B::Ptr;
and that's not possible
As others have noted, you cannot forward-declare typedefs. That's in part because typedefs aren't really "types" of their own, but aliases for other types (hence the C++11 equivalent notion of a "type alias" such as "using Int = int;"). That means, for example, that typedefs don't show up in ABI elements such as mangled names, and so the compiler really has to know enough of the underlying type to satisfy all ABI requirements (including how to mangle the type name).
You cannot.
But you can decouple the Ptr definition of the classes:
class A;
class B;
template <typename T>
struct Traits {
typedef std::shared_ptr<A> Ptr;
};
class A
{
Traits<B>::Ptr foo();
};
class B
{
Traits<A>::Ptr bar();
};
If A and B does not share the same types, you always can specialize Traits for all type.
You're facing two distinct difficulties: 1. There are no forward declarations of typedefs 2. Forward declarations of nested types are not possible
There is no way around the second: you have to unnest the types.
One way around the first that I occasionally use is to make a derived type, and that yes, can be forwardly declared.
Say:
struct Ptr : shared_ptr<A> {};
This is a new type, but it is almost the same as a synonym. The problem, of course, is constructors, but that is getting better with C++11.
This answer, of course, is in general. For your specific case, I think you should define the Ptrs outside the classes and you would have no problem at all.
struct A;
struct B;
typedef shared_ptr<A> APtr;
typedef shared_ptr<B> BPtr;
and then the classes.