Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr with templates

If I want to create a smart pointer to struct I do that:

    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 a template struct like that:

    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 should I declare the B_Ptr ?

like image 705
cpp_fanatic Avatar asked Nov 10 '09 18:11

cpp_fanatic


3 Answers

That would be

typedef shared_ptr< B<char> > B_Ptr;
B_Ptr p( new B<char> );
p->value = 'w';
like image 155
xtofl Avatar answered Oct 20 '22 19:10

xtofl


If you are interested in a fixed template type for B, then I throw my support behind xtofl's answer. If you're interested in later specifying B's template argument, C++ doesn't allow you to do this (though it will be changed in C++0x). Typically what you're looking for is this kind of workaround:

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

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

(Thanks to UncleBens for the improvements.)

like image 27
fbrereto Avatar answered Oct 20 '22 17:10

fbrereto


What you want is not yet possible in C++. You want "template typedefs" which 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 guess you could do something similar in C++98 with a macro if you really want to.

like image 27
sellibitze Avatar answered Oct 20 '22 19:10

sellibitze