、あなたはおそらく、単に非テンプレートオーバーロードを定義する方がいいでしょう:
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;
}
これは今幸せに合計します:あなたのコードはOKのようだとして
std::unordered_map<std::string, int>
、および std::map<std::string, int>
、
なく std::map<int, std::string>
いいえ(1)はテンプレートです(2)は和の過負荷である。 – coincoin