shared_ptr与模板

cpp*_*tic 5 c++ templates shared-ptr

如果我想创建一个指向struct的智能指针,我会这样做:

    struct A
    {
        int value;
    };
    typedef boost::shared_ptr<A> A_Ptr;
Run Code Online (Sandbox Code Playgroud)

所以,我可以写下面的内容:

    A_Ptr pA0(new A);
    pA0->value = 123;
Run Code Online (Sandbox Code Playgroud)

但是,如果我有这样的模板结构:

    template<typename T>
    struct B
    {
        T value;
    };
Run Code Online (Sandbox Code Playgroud)

我想写下面的内容:

    B_Ptr<char> pB0(new B<char>);
    pB0->value = 'w';
Run Code Online (Sandbox Code Playgroud)

那么,我该如何申报B_Ptr?

fbr*_*eto 7

如果您对固定模板类型感兴趣B,那么我将支持xtofl的答案.如果您对以后指定B模板参数感兴趣,C++不允许您这样做(尽管它将在C++ 0x中更改).通常你正在寻找的是这种解决方法:

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

B_Ptr<char>::type pB0 = ...;
Run Code Online (Sandbox Code Playgroud)

(感谢UncleBens的改进.)

  • 或许:`template <class T> struct T_Ptr {typedef boost :: shared_ptr <B <T>> type; }; T_Ptr <char> :: type x;` (2认同)

xto*_*ofl 7

那就是

typedef shared_ptr< B<char> > B_Ptr;
B_Ptr p( new B<char> );
p->value = 'w';
Run Code Online (Sandbox Code Playgroud)


sel*_*tze 6

你想要的在 C++ 中还不可能实现。您需要“模板 typedef”,它在 C++0x 中称为“别名声明模板”:

template<typename T>
struct A {};

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

int main() {
    APtr<int> foo;
}
Run Code Online (Sandbox Code Playgroud)

我想如果你真的愿意的话,你可以用宏在 C++98 中做类似的事情。