标准::映射转换器模板
std::map transformer template
以下用于std::map
转换函数的模板不起作用。如果我使用transform_map()
,编译器无法推断出类型来查找模板。怎么能做到呢?
template <class Key, class FromValue, class ToValue, class Transformer>
std::map<Key, ToValue> transform_map(const std::map<Key, FromValue>& _map,
Transformer _tr) {
std::map<Key, ToValue> res;
std::for_each(_map.cbegin(), _map.cend(),
[&res, &_tr](const std::pair<const Key, FromValue>& kv) {
res[kv.first] = _tr(kv.second);
});
return res;
}
函数模板的推导是根据您传入的参数完成的。由于ToValue
与任何传入的参数无关,因此无法推断。
您可以通过告诉编译器默认为使用FromValue
调用Transformer
时将返回的值来解决此问题。
#include <iostream>
#include <map>
#include <algorithm>
template <class Key, class FromValue, class Transformer, class ToValue = decltype(std::declval<Transformer>()(std::declval<FromValue>()))>
std::map<Key, ToValue> transform_map(const std::map<Key, FromValue>& _map,
Transformer _tr) {
std::map<Key, ToValue> res;
std::for_each(_map.cbegin(), _map.cend(),
[&res, &_tr](const std::pair<const Key, FromValue>& kv) {
res[kv.first] = _tr(kv.second);
});
return res;
}
int main ()
{
std::map<int, double> m1 {{1, 1.5}, {2, 2.5}};
auto m2 = transform_map(m1, [](double d){ return static_cast<int>(d); });
for (auto& p : m1)
std::cout << p.first << " " << p.second << std::endl;
for (auto& p : m2)
std::cout << p.first << " " << p.second << std::endl;
}
相关文章:
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 定义具有非标准签名的自定义映射比较器
- 如何将整数向量插入到键中,标准::映射的值
- 标准::映射::合并的计算时间复杂度
- 标准::映射转换器模板
- 从另一个常量标准::映射初始化一个常量标准::映射的一部分
- 替换标准::映射值时崩溃
- 标准::键映射和/或 boost::any 类型的值的类型检查
- 如果可能,标准::映射分配是否静态
- 如何在标准::映射中try_emplace POD 结构?
- 如何通过套接字传输标准::多映射数据
- 多类型标准映射
- 五月标准::映射键地址值数
- 处理对存储在私有映射中的值的封装访问的标准方法,而不破坏C++中的抽象
- 模板标准::映射为类成员
- 模板标准::映射::迭代器实例化
- C++ 如何在标准::多映射中插入
- 推进标准映射的迭代器
- 标准::映射 标准::集合包含重复的键
- std::映射标准分配器性能与块分配器