6

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 ?

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
cpp_fanatic
  • 91
  • 1
  • 1
  • 7

4 Answers4

8

That would be

typedef shared_ptr< B<char> > B_Ptr;
B_Ptr p( new B<char> );
p->value = 'w';
xtofl
  • 40,723
  • 12
  • 105
  • 192
7

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

fbrereto
  • 35,429
  • 19
  • 126
  • 178
  • @Martin: How so? His wording of the question is vague enough that I'm not convinced he was looking for a fixed type, and my answer is a reasonable solution in the case he is not. – fbrereto Nov 10 '09 at 19:30
  • 2
    Or perhaps: `template struct T_Ptr{ typedef boost::shared_ptr > type; }; T_Ptr::type x;` – UncleBens Nov 10 '09 at 19:49
  • @fbrereto: I find the question clear and concise. Why does this not work. You are adding another layer of indirection that is not required and just makes it harder to read without providing any benefit to a maintainer. – Martin York Nov 11 '09 at 09:42
6

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.

sellibitze
  • 27,611
  • 3
  • 75
  • 95
3

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>());
Rost
  • 8,779
  • 28
  • 50