Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance instead of typedef

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?

like image 401
Daniel A. White Avatar asked Jan 14 '09 02:01

Daniel A. White


4 Answers

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;
};
like image 200
Magnus Hiie Avatar answered Nov 20 '22 00:11

Magnus Hiie


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;
like image 23
Dave Ray Avatar answered Nov 20 '22 00:11

Dave Ray


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>.

like image 40
Max Lybbert Avatar answered Nov 19 '22 23:11

Max Lybbert


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.

like image 31
user877329 Avatar answered Nov 19 '22 23:11

user877329