Re: Templates specialization
On 2007-07-10 13:18, Aarti wrote:
I am trying to write a function to count the number of occurances of a
particular element in an array. I am also trying to specialize the
function for strings. I am passing the array as reference to the
function. Is there a way I can avoid hardcoding the size of the
array? I know we can do it if we pass the array as a pointer but can
we do it for pass by reference?
#include <iostream>
#include <string>
using std::cout;
using std::string;
template<typename T, int len>
int my_count(T (&arr)[len], T ele)
{
int count = 0;
cout << "LEN = " << len << std::endl;
for(int i=0; i< len; ++i)
{
if(arr[i] == ele)
++count;
}
return count;
}
Don't specialise, overload:
template<int len>
int my_count(string (&arr)[len], string ele)
{
int count = 0;
cout << "LEN = " << len << std::endl;
for(int i=0; i< 3; ++i)
{
if(arr[i] == ele)
++count;
}
return count;
}
--
Erik Wikstr?m