struct ItemCounter
{
template<typename T1, typename T2, typename = typename std::enable_if<!std::is_same<T1, typename T2::value_type::second_type>::value>::type>
static typename T2::value_type::second_type::size_type Count(const T2 &container) {
typename T2::value_type::second_type::size_type ret = 0;
for (const auto &item : container) {
ret += ItemCounter::Count<T1>(item.second);
}
return ret;
}
template<typename T1, typename T2, typename = typename std::enable_if<!std::is_same<T1, typename T2::value_type>::value>::type>
static typename T2::value_type::size_type Count(const T2 &container) {
typename T2::value_type::size_type ret = 0;
for (const auto &item : container) {
ret += ItemCounter::Count<T1>(item);
}
return ret;
}
template<typename T1, typename T2, typename = typename std::enable_if<std::is_same<T1, typename T2::value_type>::value>::type>
static typename T2::size_type Count(const T2 &container)
{
return container.size();
}
template<typename T1, typename T2, typename = typename T2::value_type::second_type, typename = typename std::enable_if<std::is_same<T1, typename T2::value_type::second_type>::value>::type>
static typename T2::size_type Count(const T2 &container)
{
return container.size();
}
};
template<typename T, typename TContainer>
size_t ItemCount(const TContainer &container)
{
return ItemCounter::Count<T>(container);
}
代码重构时会方便很多,支持value_type为T和pair<X,T>类型的容器
例如原来:
std::vector<A> arr;
size_t sz = arr.size();
重构后:
std::map<std::string, std::vector<A> > mapped_arr;
size_t sz = ItemCount<A>(mapped_arr);