【问题标题】:I don't understand ptr_fun我不明白 ptr_fun
【发布时间】:2015-12-01 01:09:13
【问题描述】:

我在其中一个 c++ 代码中遇到了这个 ptr_fun 的东西,我尝试从 cplusplus.com 阅读它,但老实说,我无法弄清楚这个函数指针应该做什么。

感兴趣的代码非常简单,将字符串开头的空白部分剪掉。

static inline string & trim_beg(string & s) {
  s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun < int, int > (isspace))));
  return s;
}

【问题讨论】:

  • 您不必指定模板参数,ptr_fun(::isspace) 应该这样做。 ptr_fun 的唯一目的是包装isspace 并提供unary_negate 所需的成员typedef argument_typenot1 返回的东西)。所以find_if 调用将返回一个迭代器,指向!isspace 为真的第一个元素。

标签: c++ string stl


【解决方案1】:

来自 Scott Meyers 的 Effective STL(第 40 条):

ptr_fun 唯一能做的就是让一些 typedef 可用。那是 它。 not1 需要这些 typedef,这就是为什么应用 not1 到 ptr_fun 但直接将 not1 应用于 ... 不起作用。 ... 缺少 not1 所需的 typedef。

这与 Praetorian 在上述 cmets 中给出的答案基本相同,但 Effective STL 提供了更一般的解释。

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 2011-02-17
    • 2018-04-08
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 2010-09-07
    相关资源
    最近更新 更多