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].
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.
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.
Template in C++is a feature. We write code once and use it for any data type including user defined data types.
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.
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";
}
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