Shared_ptr with templates

If I want to create a smart pointer to a struct, I do this:

    struct A
    {
        int value;
    };
    typedef boost::shared_ptr<A> A_Ptr;

So, I can write the following:

    A_Ptr pA0(new A);
    pA0->value = 123;

But, if I have such a template structure:

    template<typename T>
    struct B
    {
        T value;
    };

And I want to write the following:

    B_Ptr<char> pB0(new B<char>);
    pB0->value = 'w';

So how do I declare B_Ptr?

+5
source share
4 answers

If you are interested in a fixed type of template for B, then I will refuse support for the xtofl answer. If you are interested in defining a template argument later B, C ++ does not allow you to do this (although it will be changed in C ++ 0x). Usually you are looking for this way:

template <typename T>
struct B_Ptr
{
    typedef boost::shared_ptr< B<T> > type;
};

B_Ptr<char>::type pB0 = ...;

(Thanks to UncleBens for the improvements.)

+6
source

This will

typedef shared_ptr< B<char> > B_Ptr;
B_Ptr p( new B<char> );
p->value = 'w';
+6
source

What you want is not yet possible in C ++. You want "typedefs templates" that will be known in C ++ 0x as "alias declaration templates":

template<typename T>
struct A {};

template<typename T>
using APtr = boost::shared_ptr<A<T>>;  // <-- C++0x

int main() {
    APtr<int> foo;
}

I think you could do something similar in C ++ 98 with a macro if you really want to.

+4
source

Another useful approach is to determine the type of pointer inside a class B template:

template<typename T> struct B
{
   typedef boost::shared_ptr< B<T> > SPtr;
   T value;
};

B<int>::SPtr p(new B<int>());
+2
source

All Articles