【问题标题】:Using mem_fn instead of mem_fun使用 mem_fn 代替 mem_fun
【发布时间】:2020-08-04 20:23:48
【问题描述】:

我正在尝试使用以下答案: String To Lower/Upper in C++ 但我使用的是 C++17,这意味着答案已弃用。

bind 替换bind1st 是微不足道的,现在我想用mem_fn 替换mem_fun,但由于某种原因,这对我来说并不那么简单。

我尝试了以下替换:

auto greet = std::mem_fn<wchar_t(wchar_t)>(&ctype<wchar_t>::toupper);

这给了我“找不到匹配的重载函数”错误。为什么?想坚持std::transform怎么解决?

【问题讨论】:

  • 使用 lambda 代替bind,那么你就不用担心mem_fn

标签: c++ visual-c++ c++17


【解决方案1】:

std::mem_fn声明中可以看到,模板参数有两个,第一个是函数签名,第二个是类类型。问题是您只明确指定了函数签名而不是类类型,这使得编译器必须从参数中推断出它。并且参数是重载集std::ctype&lt;wchar_t&gt;::toupper,您没有通过强制转换解决。

解决方法是将std::ctype&lt;wchar_t&gt;::toupper 指针显式转换为所需的成员指针。之后就不需要显式指定std::mem_fn的模板参数了。

using toupper_t = wchar_t (std::ctype<wchar_t>::*)(wchar_t) const;
auto greet = std::mem_fn(static_cast< toupper_t >(&std::ctype<wchar_t>::toupper));

但是,当然,只使用 lambda 会更容易。

【讨论】:

    【解决方案2】:

    避免std::bindstd::mem_fn 和朋友,使用 lambda 代替会更简单。

    例如:

    std::transform(in.begin(), in.end(), out.begin(), [&ct](wchar_t c) {
        return ct.toupper(c);
    });
    

    【讨论】:

      【解决方案3】:

      正确的拼写是:

      auto greet = std::mem_fn<wchar_t(wchar_t) const, std::ctype<wchar_t>>(
          &std::ctype<wchar_t>::toupper);
      

      或者实际上你不需要两个模板参数,只需要第一个:

      auto greet = std::mem_fn<wchar_t(wchar_t) const>(&std::ctype<wchar_t>::toupper);
      

      您缺少的重要部分是 const:它是一个 const 成员函数,您需要完整的类型。


      但你最好写 lambda:

      auto greet = [](std::ctype<wchar_t> const& ct, wchar_t c) {
          return ct.toupper(c);
      };
      

      【讨论】:

        猜你喜欢
        • 2012-07-25
        • 1970-01-01
        • 2016-09-12
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        相关资源
        最近更新 更多