11

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?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445

4 Answers4

14

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
  • 494
  • 1
  • 4
  • 14
  • std::vector has a non-virtual destructor so you need to be careful not delete a MyVectorType via a std::vector* – jk. Dec 23 '09 at 09:25
  • I was not proposing to use MyVectorType as the actual datatype, but rather MyVectorType::type, which is a typedef for std::vector, so no danger here. – Magnus Hiie Feb 04 '10 at 23:29
10

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
  • 39,616
  • 7
  • 83
  • 82
1

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
  • 19,717
  • 4
  • 46
  • 69
1

What you should use depends on how it should behave (overload resolution for example):

  • If you want it to be a new distinct type

    class Foo : public Whatever {};
    

    However, you can now pass pointers or references of Foo, to functions accepting Whatever, so this becomes a hybrid. So in this case, use private inheritance, and using Whatever::Foo or custom implementations, to expose the methods you want.

  • If you want a type synonym

    using Foo = Whatever;
    

The former has the advantage that it is possible to predeclare a class, but not a typedef.

user877329
  • 6,717
  • 8
  • 46
  • 88