Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an array as template type

Tags:

c++

templates

I need to pass an array as a template type. How can achieve it. For example, I want something like this.

Fifo<array, Q_SIZE> f; // This is a queue of arrays (to avoid false sharing)

What should I put in place of array? Assume I need an array of int. Also note that I don't want std::vector or a pointer to an array. I want the whole basic array, something equivalent of say int array[32].

like image 243
pythonic Avatar asked Apr 12 '12 16:04

pythonic


People also ask

What does template <> mean in C++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

How will you restrict the template for a specific datatype?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

Can templates be used for user defined data types?

Template in C++is a feature. We write code once and use it for any data type including user defined data types.

What is template type parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.


1 Answers

Try this:

Fifo<int[32], Q_SIZE> f; 

Like this:

#include <iostream>
template <class T, int N>
struct Fifo {
  T t;
};

int main () {
 const int Q_SIZE  = 32;
 Fifo<int[32],Q_SIZE> f;
 std::cout << sizeof f << "\n";
}
like image 72
Robᵩ Avatar answered Oct 19 '22 10:10

Robᵩ