对于具体类型,你可能会更好过简单地定义一个非模板超载:
double Sum(const std::map<std::string, double> &m) // (1) function template overloading
// double Sum<map<string, double> >(const map<string, double> &m) // (2) explicit specialization
{
double sum = 0;
std::map<std::string, double>::const_iterator i; // obtain Iterator from Container
for (i = m.begin(); i != m.end(); i++) { sum += i->second; } // sum. ('first' is index, 'second' is data)
return sum;
}
模板是比较有用的通用功能:
//
// sum any map's arithmetic mapped values
//
template<class K, class V, class C, class A>
typename std::map<K, V, C, A>::mapped_type
Sum(const std::map<K, V, C, A> &m) // (1) function template overloading
{
using map_type = std::map<K, V, C, A>;
using mapped_type = typename map_type::mapped_type;
using const_iterator = typename map_type::const_iterator;
mapped_type sum = 0;
const_iterator i; // obtain Iterator from Container
for (i = m.begin(); i != m.end(); i++) { sum += i->second; } // sum. ('first' is index, 'second' is data)
return sum;
}
.. (C++ 14)...
namespace notstd {
template<class...>
using void_t = void;
}
template< class, class = notstd::void_t<> >
struct supports_mapped_type : std::false_type { };
template< class T >
struct supports_mapped_type<T, notstd::void_t<typename T::mapped_type>> : std::true_type { };
template< class, class = notstd::void_t<> >
struct supports_const_iterator : std::false_type { };
template< class T >
struct supports_const_iterator<T, notstd::void_t<typename T::const_iterator>> : std::true_type { };
template<class T> static constexpr bool IsMaplike = supports_mapped_type<T>() and supports_const_iterator<T>();
template<class MapLike,
std::enable_if_t<
IsMaplike<MapLike> and std::is_arithmetic<typename MapLike::mapped_type>()
>* = nullptr>
typename MapLike::mapped_type
Sum(const MapLike &m) // (1) function template overloading
{
using map_type = MapLike;
using mapped_type = typename map_type::mapped_type;
using const_iterator = typename map_type::const_iterator;
mapped_type sum = 0;
const_iterator i; // obtain Iterator from Container
for (i = m.begin(); i != m.end(); i++) { sum += i->second; } // sum. ('first' is index, 'second' is data)
return sum;
}
这将现在高兴地总结:
std::unordered_map<std::string, int>
,并 std::map<std::string, int>
,
但不 std::map<int, std::string>
否(1)是模板专业化和(2)是Sum的超负荷。 – coincoin