I'm playing around with templates. I'm not trying to reinvent the std::vector, I'm trying to get a grasp of templateting in C++.
Can I do the following?
template <typename T>
typedef struct{
size_t x;
T *ary;
}array;
What I'm trying to do is a basic templated version of:
typedef struct{
size_t x;
int *ary;
}iArray;
It looks like it's working if I use a class instead of struct, so is it not possible with typedef structs?
You don't need to do an explicit
typedef
for classes and structs. What do you need thetypedef
for? Further, thetypedef
after atemplate<...>
is syntactically wrong. Simply use:You can template a struct as well as a class. However you can't template a typedef. So
template<typename T> struct array {...};
works, buttemplate<typename T> typedef struct {...} array;
does not. Note that there is no need for the typedef trick in C++ (you can use structs without thestruct
modifier just fine in C++).The syntax is wrong. The
typedef
should be removed.From the other answers, the problem is that you're templating a typedef. The only "way" to do this is to use a templated class; ie, basic template metaprogramming.
The Standard says (at 14/3. For the non-standard folks, the names following a class definition body (or the type in a declaration in general) are "declarators")
Do it like Andrey shows.
The problem is you can't template a typedef, also there is no need to typedef structs in C++.
The following will do what you need