Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forward declare templated type that should belong to a class?

Assume I have 2 classes:

class A
{
public:
  typedef std::shared_ptr<A> Ref;
  ...

private:
  B::Ref _b;
}

class B
{
public:
  typedef std::shared_ptr<B> Ref;
  ...

private:
  A::Ref _a;
}

This obviously requires forward declaration of class B and B::Ref. Forward declaring B is simple, but how to do that for B::Ref too?

like image 258
Mike Lischke Avatar asked Sep 29 '14 09:09

Mike Lischke


2 Answers

One of way to solve this is

class A;
class B ;

template <typename T>
struct Traits {
    typedef std::shared_ptr<T>  Ptr; 
};


class A
{
    private:
      Traits<B>::Ptr _b;
};

class B
{
    private:
      Traits<A>::Ptr _a;
};
like image 110
P0W Avatar answered Oct 11 '22 18:10

P0W


You can't forward declare a nested typedef since at the point of the forward declaration B would be an incomplete type. You can however solve your problem like below:

class B;

class A {
  std::shared_ptr<B> _b;
public:
  typedef std::shared_ptr<A> Ref;
};

class B {
  A::Ref _a;
public:
  typedef std::shared_ptr<B> Ref;
};
like image 41
101010 Avatar answered Oct 11 '22 17:10

101010