Jul 10, 2008 at 12:01pm UTC
The following problem uses template to compare two value, whether it be int, double or string type. I have specified the string type method as thus: It should NOT be case sensitive, but it doesn't call the specific template, it became case sensitive, which is not I want. What's wrong?
#include <iostream>
#include <vector>
#include <string>
template <typename value_type>
value_type max(value_type x, value_type y){
return x > y ? x : y;
}
template<>
std::string const & max<std::string const &>(std::string const & first, std::string const & second){
std::string s1(first);
std::string s2(second);
std::transform(s1.begin(), s1.end(), s1.begin(), tolower);
std::transform(s1.begin(), s1.end(), s2.begin(), tolower);
return s1 > s2 ? first : second;
}
typedef std::string value_t;
value_t const limit("END");
std::string type("words");
int main(){
std::vector<value_t> data;
value_t value;
std::cout << "Type in some " << type << ".\n";
do{
std::cin >> value;
data.push_back(value);
} while(value != limit);
value_t maximum(limit);
for(size_t i(0); i != data.size(); ++i){
maximum = max<value_t>(maximum, data[i]);
}
std::cout << "The largest input value was " << maximum << ".\n";
return 0;
}
Jul 10, 2008 at 12:38pm UTC
This max<> template won't work with floating point since you can't use the arithmetic comparison operators ( <, > , ==, etc) with floating point.
Do a Google on floating point aritmetic and you will see what I mean.