【发布时间】:2018-11-25 15:24:21
【问题描述】:
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? -
您可以将
class ToValue移动到class FromValue之前。那么你只需要指定Key和ToValue模板参数,其他的会被推导出来。