标准::映射转换器模板

std::map transformer template

本文关键字:映射 标准 转换器      更新时间:2023-10-16

以下用于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;
}