Reputation: 21615
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].
Upvotes: 9
Views: 28951
Reputation: 39496
The std::end
function in C++ 11 has an overload for array types that nicely demonstrate this.
Here's a possible implementation of it:
template< class T, std::size_t N >
T* end(T(&array)[N]) {
return array + N;
}
If you need an object that wraps an array, a templated factory function will help creating 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);
}
Upvotes: 3
Reputation: 21615
Well I've found a solution. I can wrap the array in a structure, such as below.
typedef struct
{
int array[32];
} my_array;
Then I can use it as follows.
Fifo<my_array, Q_SIZE> f;
Upvotes: 3
Reputation: 12547
If you want to pass array type when creating queue you can write
template <typename Array>
struct Fifo;
template <typename T, int size>
struct Fifo<T[size]>
{
};
or just
template <typename Array>
struct Fifo
{
};
and use it like
int main()
{
Fifo<int[10]> fa;
}
Then, you should understand, that int[10]
is completely different type from int[11]
, and once you created Fifo<int[10]>
you cannot store here arrays of size 11 or 9 anymore.
Upvotes: 3
Reputation: 168626
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";
}
Upvotes: 7