Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct with template variables in C++

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?

like image 352
monkeyking Avatar asked Mar 15 '10 15:03

monkeyking


People also ask

Can struct have template?

The entities of variable, function, struct, and class can have templates, which involve declaration and definition. Creating a template also involves specialization, which is when a generic type takes an actual type. The declaration and the definition of a template must both be in one translation unit.

What is variable template?

A variable template defines a family of variable (when declared at namespace scope) or a family of static data members (when defined at class scope).

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.

What is template data structure?

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.


2 Answers

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;  };  
like image 86
Binary Worrier Avatar answered Sep 20 '22 17:09

Binary Worrier


template <typename T> struct array {   size_t x;   T *ary; }; 
like image 21
Andrey Avatar answered Sep 20 '22 17:09

Andrey