Chris Morris
Chris Morris

Reputation: 4444

typedef a shared pointer that contains a templated class

Suppose I have some template class forward declared and I want to typedef a shared pointer to it. How would I do this?

template<typename T> class Arg;
typedef std::tr1::shared_ptr<Arg> ArgPtr; // Compiler error

Upvotes: 2

Views: 2902

Answers (2)

Morwenn
Morwenn

Reputation: 22562

That's because Arg is not really a type. Arg<int> for example would be one. That's why the compiler does not want to compile. You should have written that for example:

template<typename T> class Arg;
typedef std::tr1::shared_ptr<Arg<int>> ArgPtr;

If you used C++11, I guess you could have written that:

template<typename T> class Arg;

template<typename T>
using ArgPtr = std::tr1::shared_ptr<Arg<T>>;

Upvotes: 2

dirkgently
dirkgently

Reputation: 111140

You also probably want template typedef. Read up on Sutter's article.

In C++03, you need a hack as:

template <typename Arg> struct ArgPtr {
     typedef std::shared_ptr<Arg> ArgPtrType;
};

In C++11, you can use template aliasing directly with the using keyword:

template <typename T>
using ArgPtrType = std::shared_ptr<Arg<T>>;

Upvotes: 7

Related Questions