views:

682

answers:

3

C++ is unable to make a template out of a typedef or typedef a templated class. I know if I inherit and make my class a template, it will work.

Examples:

// Illegal
template <class T>
typedef MyVectorType vector<T>;

//Valid, but advantageous?
template <class T>
class MyVectorType : public vector<T> { };

Is doing this advantageous so that I can "fake" a typedef or are there better ways to do this?

+8  A: 

Inheritance is not what you want. A more idiomatic approach to emulating a templated typedef is this:

template <typename T> struct MyVectorType {
    typedef std::vector<T> t;
};

Refer to the typedef like this:

MyVectorType<T>::t;
Dave Ray
+11  A: 

C++0x will add template typedefs using the using keyword.

Your solution declares a new type, not a type "alias", e.g. you cannot initialize a MyVectorType & (reference) with a vector<T>. This might not be a problem for you, but if it is, but you don't want to reference vector in your code, you can do:

template <typename T>
class MyVectorType {
public:
  typedef std::vector<T> type;
};
Magnus Hiie
std::vector has a non-virtual destructor so you need to be careful not delete a MyVectorType via a std::vector*
jk
I was not proposing to use MyVectorType as the actual datatype, but rather MyVectorType<T>::type, which is a typedef for std::vector<T>, so no danger here.
Magnus Hiie
+1  A: 

C++ is unable to make a template out of a typedef or typedef a templated class.

That depends on what you mean by typedef: std::vector<size_t> is legal -- even though size_t is a typedef -- and std::string is a typedef for std::basic_string<char>.

Max Lybbert