【发布时间】:2021-05-23 13:42:13
【问题描述】:
我想编写一个通用函数,它采用一些类似地图的类型,并返回地图中的所有键。我还希望函数的 API 非常简单,像这样:
std::unordered_map<int, std::string> stringTable;
auto stringTableKeys = keys(stringTable); // should return a std::vector<int>
std::map<std::string, double> doubleTable;
auto doubleTableKeys = keys(doubleTable); // should return a std::vector<std::string>
我不希望它被绑定到 std::map 或 std::unordered_map,我也不希望被绑定到特定的键或值类型,所以我尝试编写以下内容:
template <typename Key, typename Value, template <typename, typename...> typename Table>
std::vector<Key> keys(const Table<Key, Value>& table)
{
std::vector<Key> keys;
keys.reserve(table.size());
for (const auto& [key, value] : table)
keys.push_back(key);
return keys;
}
但是,如果我想使用这个版本的 keys() 函数,我必须这样调用它
auto stringTableKeys = keys<int, std::string, std::unordered_map>(stringTable);
如何在keys()的定义中指定模板,让调用者不必指定类型?
【问题讨论】:
-
如果您的函数已经依赖于假设您编写的基于范围的
for循环可以正常工作,我不确定使用key_type会失去更多的通用性.例如。只需将MapType作为类模板参数并返回std::vector<MapType::key_type>。 -
我错过了什么吗?你的尝试似乎是work?