0

I have a templated class Foo, of which I want to typedef smart pointers.

AFAIK I can't typedef this outside the class. The code below (or variants of it) won't work.

template<typename T>
typedef shared_ptr< Foo<T> > Foo_Ptr<T>; 

So I have typedefed shared_ptr and weak_ptr inside the class.

template<typename T>
class Foo {
public:
    typedef shared_ptr< Foo<T> > Ptr;
    typedef weak_ptr< Foo<T> > WeakPtr;
};

Which is annoying because I can't forward declare it now in other headers.

But my question is, whenever I want to declare a Foo::Ptr I have to precede it with typename. e.g.

template<typename T>
class Bar {
   void do(typename Foo<T>::Ptr p);
}

This syntax is a bit cumbersome, it's actually quicker to write shared_ptr<Foo<T>>

Is there any alternatives? I.e. a way of declaring Foo::Ptr (or even Foo::Ptr) in any context which is templated to T? (e.g. inside the class Bar?)


EDIT.

Based on Denis's answer, I'm thinking of going with this

types.h

template<typename T>
class Foo;

template<typename T>
using Foo_Ptr = std::shared_ptr< Foo<T> >;

template<typename T>
class Bar;

template<typename T>
using Bar_Ptr = std::shared_ptr< Bar<T> >;

Foo.h

#include "types.h"
template<typename T>
class Foo {
public:

};

elsewhere

#include "Foo.h"

template<typename T>
void do_sth(Foo_Ptr<T> p) {
}
memo
  • 3,554
  • 4
  • 31
  • 36

1 Answers1

3

You could introduce an alias with using like the stdlib does it for type_traits (like std_enable_if_t), which doesn't require the typename keyword:

using foo_ptr_t = typename Node<T>::Ptr;

A possible example is:

#include <memory>

template<typename>
struct Foo { };

template<typename T>
class Node {
public:
    typedef std::shared_ptr<Foo<T>> Ptr;
    typedef std::weak_ptr<Foo<T>> WeakPtr;
};

template<typename T>
using foo_ptr_t = typename Node<T>::Ptr;

void do_sth(foo_ptr_t<int> p) { }

Demo

Naios
  • 1,513
  • 1
  • 12
  • 26
  • oh that's great thanks. I wasn't aware of this 'using' alias syntax. From what I've read it's a superset of typedef, and I can use it with templates? So I could remove the shared_ptr typedefs from inside the class and have them all outside? I'll update my question with proposed code (it compiles in the compiler explorer) – memo Jan 29 '16 at 16:58