Pass array as pattern type

I need to pass an array as a template type. How can this be achieved. 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 add instead of an array? Suppose I need an int array. Also note that I don't want std::vector or a pointer to an array. I want the whole base array, equivalent to say int array [32].

+6
source share
4 answers

Try the following:

 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"; } 
+5
source

If you want to pass an array type when creating a queue, you can write

 template <typename Array> struct Fifo; template <typename T, int size> struct Fifo<T[size]> { }; 

or simply

 template <typename Array> struct Fifo { }; 

and use it like

 int main() { Fifo<int[10]> fa; } 

Then you should understand that int[10] completely different from int[11] , and after creating Fifo<int[10]> you can no longer store arrays of size 11 or 9.

+3
source

The std::end function in C ++ 11 has an overload for array types that demonstrate this well. It can be executed here:

 template< class T, std::size_t N > T* end(T(&array)[N]) { return array + N; } 

If you need an object that wraps an array, the templated factory function will help you create it:

 template< class T, std::size_t N > struct fifo { T(&array)[N]; }; template< class T, std::size_t N > fifo<T,N> make_fifo(T(&array)[N]) { return Fifo<T,N>{ array }; } int main() { int arr[] = { 1,2,3,4,5 }; // Create object from array using template argument deduction auto fifo = make_fifo(arr); } 
+2
source

Well, I found a solution. I can wrap the array in a structure like below.

 typedef struct { int array[32]; } my_array; 

Then I can use it as follows.

 Fifo<my_array, Q_SIZE> f; 
+1
source

Source: https://habr.com/ru/post/913059/


All Articles