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 boost::shared_ptr<A> Ptr;
B::Ptr foo();
};
class B
{
typedef boost::shared_ptr<B> Ptr;
A::Ptr bar();
};
I suppose I could just do the following:
boost::shared_ptr<B> foo();
But is there a more elegant solution?
But you can't forward declare a typedef. Instead you have to redeclare the whole thing like so: typedef GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator> > Value; Ah, but I don't have any of those classes declared either.
In Objective-C, classes and protocols can be forward-declared like this: @class MyClass; @protocol MyProtocol; In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.
You cannot forward declare a nested structure outside the container. You can only forward declare it within the container. Create a common base class that can be both used in the function and implemented by the nested class.
Classes and structures can have nested typedefs declared within them.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With