13

I love using smart pointers, and have seen a bit of code which makes nice use of typedefs make make them prettier. For example:

struct A {
    typedef boost::shared_ptr<A> pointer;
};

allows me to write: A::pointer a(new A);

But I have hit a minor snag in my typedef happiness :-/, forward declarations...

So imagine this scenario:

struct B;
struct A {
    boost::shared_ptr<B> b_;
};

struct B {
    boost::shared_ptr<A> a_;
};

works well enough, but I'd love to clean that up a little. Unfortunately, this is doesn't work

struct B;
struct A {
    typedef boost::shared_ptr<A> pointer;
    B::pointer b_; // <-- error here
};

struct B {
    typedef boost::shared_ptr<B> pointer;
    A::pointer a_;
};

I understand why, at that point in the file, the compiler has no information that B in fact has a type in it named pointer.

I have a feeling that I am stuck using the old approach at least for some stuff, but I'd love to hear some clever ideas.

Evan Teran
  • 87,561
  • 32
  • 179
  • 238

3 Answers3

6

That use of typedefs doesn't make it prettier- it's worthless. You can make a shared_ptr to an incomplete type, so just use shared_ptr<B>.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Agree, just leave a comment that the rest of the code should use B::pointer, as the types will be equivalent – totowtwo Jun 16 '11 at 20:29
4

If you want to share typedefs you probably want to use namespaces for declaring them:

struct A;
struct B;

namespace Aimpl {
  typedef boost::shared_ptr<A> pointer;
}

namespace Bimpl {
  typedef boost::shared_ptr<B> pointer;
}

struct A {
    Bimpl::pointer b_;
};

struct B {
    Aimpl::pointer a_;
};
Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
3

I can think of two approaches:

  • You could create a ptr_for template and use it something like this ptr_for<B>::type b_ptr_;
  • You could pimpl the two structs (I know this probably isn't what you're looking for) so the definitions of the implementations can both appear after the definitions of A and B.
Mark B
  • 95,107
  • 10
  • 109
  • 188