Solved
Template Function Specialization
Posted on 2001-09-04
In my main program I am trying to specialize a template function for int as well as char*. However, when I compile I get 2 errors. I'm not sure what I'm doing wrong. Here is my code:
template<class T>
T randomItem(int len)
{
return (T)0;
};
//specialization for int
//this function returns a random number of length len
template<>
int randomItem(int len)
{
RandomAtom<int> atom(clock()); //a class i wrote for generating random digits or lowercase letters
int thisDigit = 0;
int retVal = 0;
// first digit cannot be zero
while (thisDigit == 0) thisDigit = atom.randomIntChar();
while (len--)
{
retVal *= 10;
retVal += thisDigit;
thisDigit = atom.randomIntChar();
}
return retVal;
}
//specialization for char*
//this function returns a random string of length len
template<>
char* randomItem(int len)
{
return(randomString(len));
}
When I compile I get two errors:
1.error C2556: 'char *__cdecl randomItem(int)' : overloaded function differs only by return type from 'int __cdecl randomItem(int)'
see declaration of 'randomItem'
2.error C2040: 'randomItem' : 'char *(int)' differs in levels of indirection from 'int (int)'
Then if I switch the order of the two functions ( put the char* specialization before the int specialization ) I get the same errors only the other way around. Are you only allowed to write 1 specialization? I am using Microsoft Visual C++ 6.0 with service pack 5.