【问题标题】:std::map transformer templatestd::map 转换器模板
【发布时间】: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 之前。那么你只需要指定KeyToValue模板参数,其他的会被推导出来。

标签: c++ templates transform


【解决方案1】:

函数模板的推导是在你传入的参数上完成的。由于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;
}

【讨论】:

  • 哇,这真的很有帮助,解决了我的很多模板问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-03
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2016-08-16
  • 2018-11-06
相关资源
最近更新 更多