Let's assume that I have a function that prints a set of numbers: 1, 2, 3, 4, 5
and these numbers can either be stored as an array, or, as a vector. In my current system I therefore have two functions that accept either of these parameters.
void printNumbers(std::vector<double> &printNumbers)
{
//code
//....
}
And therefore one that accepts an array..
void printNumbers(int* numbers)
{
//code
//...
}
This seems a waste of code, and, I was thinking that I could better take advantage of code re-use which got me thinking to this: Can I use a template to determine which type of input is being passed to the function? For example, whether it's a vector
or an array
or just a single integer value?
Here is the prototype below:
#include <iostream>
using namespace std;
template<class T>
void printNumbers(T numbers)
{
// code
// code
}
int main(int argc, char *argv[]) {
int numbers[] = {1, 2, 3, 4, 5};
printNumbers<array> (numbers);
}
Any help would be greatly appreciated.