Forward declare typedef within C++ class

Tom picture Tom · Jun 6, 2013 · Viewed 14.3k times · Source

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?

Answer

Ralph Tandetzky picture Ralph Tandetzky · Jun 6, 2013

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.