好吧,如前所述,编译器无法推断出作为参数的迭代器的容器类型Sum
。
std::map<X,Y>::iterator::value_type
但是,可以使用一对值这一事实std::pair<XX, YY>
。当然,这不会限制对Sum
迭代器的期望特化std::map
,而是限制任何返回一对元素的容器迭代器(例如std::vector< std::pair<std::string, double> >
。)
如果这不打扰您,或者如果 sthg likestd::vector< std::pair<std::string, double> >
应该使用相同的专业化,那么以下代码似乎可以在您的情况下给出所需的结果:
#include <map>
#include <string>
#include <iostream>
#include <cassert>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/remove_reference.hpp>
// a small structure to
template <class U>
struct is_a_key_pair_it
{
typedef boost::false_type type;
};
template <class A, class B>
struct is_a_key_pair_it< std::pair<A, B> >
{
typedef boost::true_type type;
};
// using boost::disable_if to avoid the following code to be instanciated
// for iterators returning a std::pair
template <typename T>
const double Sum(T start_iter, T end_iter,
typename boost::disable_if<
typename is_a_key_pair_it<
typename boost::remove_reference<typename T::value_type>::type
>::type >::type * dummy = 0)
{
// code...
std::cout << "non specialized" << std::endl;
return 0;
}
// using boost::enable_if to limit the following specializing of Sum
// to iterators returning a std::pair
template <typename T>
const double Sum(T start_iter, T end_iter,
typename boost::enable_if<
typename is_a_key_pair_it<
typename boost::remove_reference<typename T::value_type>::type
>::type >::type * dummy = 0)
{
// different code...
std::cout << "specialized" << std::endl;
return 1;
}
int main()
{
typedef std::map<std::string, double> map_t;
// check
assert(is_a_key_pair_it<map_t::iterator::value_type>::type::value);
// works also for const_iterators
assert(is_a_key_pair_it<map_t::const_iterator::value_type>::type::value);
map_t test_map;
test_map["Line1"] = 10; // add some data
test_map["Line2"] = 15;
double ret = Sum(test_map.begin(),test_map.end());
}