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?
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.
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).
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.
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.
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; };
template <typename T> struct array { size_t x; T *ary; };
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