2

I was wondering if it is possible to have some kind of parameterized typedef.

To illustrate, in my code I use this typedef:

typedef std::queue<std::vector<unsigned char>, std::deque<std::vector<unsigned char> > > UnsignedCharQueue;

As you can see this is a rather unwieldy construct so the typedef makes sense. However, if I want to have queues with other datatypes I need to define them beforehand explizitly.

So I was thinking if it were possible to use a construct like this:

typedef std::queue<std::vector<T>, std::deque<std::vector<T> > > Queue<T>;

private:
    Queue<unsigned char> mMyQueue;

Similar like generics in Java.

Vaughn Cato
  • 59,967
  • 5
  • 75
  • 116
Devolus
  • 20,356
  • 11
  • 56
  • 104
  • 1
    possible duplicate of [C++ template typedef](http://stackoverflow.com/questions/2795023/c-template-typedef) –  Apr 30 '13 at 18:40

2 Answers2

10

In C++11, you can use template aliases, such as in:

template<typename T>
using my_alias = some_class_template<T>;

// ...
my_alias<T> obj; // Same as "some_class_template<T> obj;"

So in your case it would be:

template<typename T>
using Queue = std::queue<std::vector<T>, std::deque<std::vector<T> > >;

Also notice, that in C++11 you do not need to leave a space between closed angle brackets, so the above can be rewritten as follows:

template<typename T>
using Queue = std::queue<std::vector<T>, std::deque<std::vector<T>>>;
//                                                               ^^^

In C++03 you could define a Queue metafunction this way:

template<typename T>
struct Queue
{
    typedef std::queue<std::vector<T>, std::deque<std::vector<T> > > type;
};

Which you would then use this way:

Queue<int>::type obj;

If you are using it in a template with parameter T (as in the following), do not forget the typename disambiguator:

template<typename T>
struct X
{
    typename Queue<T>::type obj;
//  ^^^^^^^^
}
Andy Prowl
  • 114,596
  • 21
  • 355
  • 432
2

Yes, it works like this:

template <typename T> using Queue = std::queue<std::vector<T>, std::deque<std::vector<T> > >;
Vaughn Cato
  • 59,967
  • 5
  • 75
  • 116