Template Syntax in C++
- by Crystal
I don't understand templates really and was trying to run a simple find the minimum for ints, doubles, chars.
First question, why is template<typename T> sometimes used, and other times template<>?
Second question, I do not know what I am doing wrong with the following code below:
#include <iostream>
template <typename T>
T minimum(T arg1, T arg2)
{
return arg1 < arg2 ? arg1 : arg2;
}
template <typename T>
// first I tried template <> instd of above, but wasn't sure the difference
T minimum<const char *>(const char *arg1, const char *arg2)
{
return strcmp(arg1, arg2) ? arg2 : arg1;
}
int main()
{
std::cout << minimum<int>(4, 2) << '\n';
std::cout << minimum<double>(2.2, -56.7) << '\n';
std::cout << minimum(2.2, 2) << '\n';
}
Compile Errors:
error C2768: 'minimum' : illegal use of explicit template arguments
error C2783: 'T minimum(const char *,const char *)' : could not deduce template argument for 'T'
: see declaration of 'minimum'
: error C2782: 'T minimum(T,T)' : template parameter 'T' is ambiguous
: see declaration of 'minimum'
Third, in getting familiar with separating .h and .cpp files, if I wanted this minimum() function to be a static function of my class, but it was the only function in that class, would I have to have a template class as well? I originally tried doing it that way instead of having it all in one file and I got some compile errors as well that I can't remember right now and was unsure how I would do that. Thanks!