Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a type alias for a templated class

Tags:

c++

Instead of using

std::vector<Object> ObjectArray;

I would like it to be

MyArray<Object> ObjectArray;

with all the std::vector methods preserved. (like push_back(), reserve(), ...etc)

However, using

typedef std::vector MyArray;

won't work. Should I use template instead? How?

like image 761
purga Avatar asked Feb 13 '09 05:02

purga


People also ask

What is template type alias?

Type alias is a name that refers to a previously defined type (similar to typedef). Alias template is a name that refers to a family of types.

How do I create an alias in CPP?

You can use an alias declaration to declare a name to use as a synonym for a previously declared type. (This mechanism is also referred to informally as a type alias). You can also use this mechanism to create an alias template, which can be useful for custom allocators.

Is C++ an alias of C#?

C++ is not the alias of C# programming language.

Which entities can be templated C++?

A template is a C++ entity that defines one of the following: a family of classes (class template), which may be nested classes. a family of functions (function template), which may be member functions.


1 Answers

What you would really want is a templated typedef. Unfortunately those are not supported in the current version of C++, but they will be added in C++0x.

For now, here's a possible workaround:

template<class T> struct My {
    typedef std::vector<T> Array;
};

My<Object>::Array ObjectArray

Whether or not that is better than simply using std::vector directly, I'll leave to you to decide.

like image 144
Thomas Avatar answered Sep 19 '22 11:09

Thomas