简体   繁体   中英

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 ?

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.)

That would be

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

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.

Another useful approach is to define pointer type inside B class template:

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

B<int>::SPtr p(new B<int>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM