Search code examples
c++classtemplatesshared-ptrforward-declaration

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

Solution

  • 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>>;