我想编写一个模板函数,它接受一个键值对的容器(例如map<K,V>
或vector<pair<K,V>>
)并返回一个容器容器的容器。例如:
template<typename C, typename K, typename V>
vector<vector<K>> partition_keys(const C& input)
{
vector<vector<K>> result;
...
// do something
for (const auto &pair : input)
{
cout << pair.first << "," << pair.second << std::endl;
}
...
return result;
}
以下是我想称之为:
// map
map<string, string> product_categories;
partition_keys(product_categories); // doesn't work
partition_keys<map<string, string>, string, string>(product_categories); // have to do this
// vector
vector<pair<string, string>> movie_genres;
partition_keys(movie_genres); // doesn't work
partition_keys<vector<pair<string, string>>, string, string>(movie_genres); // have to do this
但是,编译器无法在不明确指定的情况下推导出模板参数K和V.我希望该函数适用于任何具有任何类型对的容器;所以我想避免为map<K,V>
,list<pair<K,V>>
,vector<pair<K,V>>
等编写单独的模板函数。
所以,我必须按照以下方式修改模板函数签名,使其按照我想要的方式工作:
template<typename C,
typename K = remove_const_t<C::value_type::first_type>,
typename V = C::value_type::second_type>
vector<vector<K>> partition_keys(const C& input);
有更好的方法吗?根据{{1}}的{{1}}来推断K
和V
的类型是一种好习惯吗?此外,调用者可能会明确传递value_type
和C
的无效参数。
另请注意我如何通过调用K
删除键类型的常量,因为对于V
,remove_const_t
是map
类型且标准不允许创建一个C::value_type::first_type
类型的集合。
答案 0 :(得分:2)
你正在采取正确的方式,更具体地说:
template<typename C,
typename Pair = typename C::value_type,
typename Key = std::remove_const_t<typename Pair::first_type>,
typename Value = typename Pair::first_type
>
vector<vector<Key>> partition_keys(const C& input)
是正确的(Demo)。但是,如果您需要对不同的模板函数使用类似的类型分解,例如:
....repeat above templated type decomposition....
vector<vector<Key>> sorted_keys(const C& input);
....repeat above templated type decomposition....
vector<vector<Key>> filtered_keys(const C& input);
打字可能太多了。在这种情况下,您可以创建一个简单的特质类来帮助您。
template<typename T>
struct PTraits{
using pair_type = typename T::value_type;
using key_type = std::remove_const_t<typename pair_type::first_type>;
using value_type = typename pair_type::second_type;
};
template<typename T>
using KeyTypper = typename PTraits<T>::key_type;
然后用作......
template<typename C, typename Key = KeyTypper<C>>
vector<vector<Key>> partition_keys(const C& input);
template<typename C, typename Key = KeyTypper<C>>
vector<vector<Key>> sorted_keys(const C& input);
template<typename C, typename Key = KeyTypper<C>>
vector<vector<Key>> filtered_keys(const C& input);
答案 1 :(得分:1)
很好。如果您不喜欢模板参数中的混乱,可以将键类型直接放在返回类型中,可能采用尾随形式:
template <typename C>
auto partition_keys(const C& input)
-> vector<vector<remove_const_t<typename C::value_type::first_type>>>;
或依赖于正常函数的返回类型推导并完全省略返回类型:
template <typename C>
auto partition_keys(const C& input)
{
vector<vector<remove_const_t<typename C::value_type::first_type>>> result;
//...
return result;
}