Struct with template variables in C++

monkeyking picture monkeyking · Mar 15, 2010 · Viewed 143.6k times · Source

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?

Answer

Binary Worrier picture Binary Worrier · Mar 15, 2010

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

template <typename T> 
struct array { 
  size_t x; 
  T *ary; 
};