Struct with template variables in C ++

I play with patterns. I am not trying to reinvent std :: vector, I am trying to understand patterns 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 the basic template version:

 typedef struct{ size_t x; int *ary; }iArray; 

It seems like it works if I use a class instead of struct, so this is not possible with typedef structs?

+44
c ++ struct class templates
Mar 15
source share
7 answers

The problem is that you cannot create a typedef template, there is also no need for typedef structures in C ++.

The following will do what you need

 template <typename T> struct array { size_t x; T *ary; }; 
+101
Mar 15 '10 at 15:33
source share
 template <typename T> struct array { size_t x; T *ary; }; 
+18
Mar 15 '10 at 15:32
source share

You do not need to make explicit typedef for classes and structures. Why do you need a typedef ? Also, typedef after a template<...> is syntactically incorrect. Just use:

 template <class T> struct array { size_t x; T *ary; } ; 
+8
Mar 15 '10 at 15:32
source share

You can create a template for both a class and a class. However, you cannot create a typedef template. So template<typename T> struct array {...}; works, but template<typename T> typedef struct {...} array; no. Note that there is no need for a typedef trick in C ++ (you can use structures without a struct modifier, just fine in C ++).

+5
Mar 15
source share

The standard says (in 14/3. For non-standard people, the names following the body of the class definition (or the type in the declaration in general) are "declarators")

An init-declarator-list in dec-laration must contain at most one declarator in a template declaration, explicit specialization, or explicit instance. When such an declaration is used to declare a class template, the declarator is not permitted.

Do it, as Andrey shows.

+4
Mar 15 '10 at 16:37
source share

The syntax is invalid. typedef should be removed.

+3
Mar 15 '10 at 17:45
source share

Of the other answers, the problem is that you are creating a typedef template. The only way to do this is to use a template class; those. basic metaprogramming of templates.

 template<class T> class vector_Typedefs { /*typedef*/ struct array { //The typedef isn't necessary size_t x; T *ary; }; //Any other templated typedefs you need. Think of the templated class like something // between a function and namespace. } //An advantage is: template<> class vector_Typedefs<bool> { struct array { //Special behavior for the binary array } } 
+3
Mar 15
source share



All Articles