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?
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;
};
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;
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>
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With