Say I had a template function that calculates the sum of a map’s elements like this:
template <class A, class B> double Total(const map<A, B>& cntr)
{
map<A, B>::const_iterator iter;
double total = 0;
for (iter = cntr.begin(); iter != cntr.end(); ++iter)
total += iter->second;
return total;
}
It would work fine whenever B was a numeric type; however, obviously if you passed in a reference to something like map<int, string>, it wouldn’t work.
I was wondering how I could test the type contained in the non-key section of the map so I can through an exception or something. I tried using isdigit() but couldn’t seem to get a working version.
EDIT: My intended use of the test would be to add functionality so that the int type is always used to calculate the total, so I can pass in map<int, string> or map<string, int> and it will always calculate the int types.
You can use type traits in C++11 or boost.
Keep in mind that types that are invalid will simply not compile, even without the assertion.