【问题标题】:boost::trim and std::bind2ndboost::trim 和 std::bind2nd
【发布时间】:2012-10-05 22:53:53
【问题描述】:

我正在尝试在字符串向量上使用boost::trim。我知道this solutions 工作得很好,但是我不明白为什么

std::for_each(df.colnames.begin(), df.colnames.end(),
    std::bind2nd(std::ptr_fun(boost::trim<std::string>), std::locale()));

不起作用。我得到错误:

error: ‘typename _Operation::result_type std::binder2nd<_Operation>::operator()(typename _Operation::first_argument_type&) const [with _Operation = std::pointer_to_binary_function<std::basic_string<char>&, const std::locale&, void>; typename _Operation::result_type = void; typename _Operation::first_argument_type = std::basic_string<char>&]’ cannot be overloaded

为什么std::bind2nd 在这里不起作用?

【问题讨论】:

    标签: c++


    【解决方案1】:

    我认为这有两个问题:

    1. ptr_fun 要求其参数返回一个值。看: http://www.sgi.com/tech/stl/ptr_fun.html

    2. bind2nd 不适用于引用参数。见:Using std::bind2nd with references

    故事的寓意: boost::bind 隐藏着惊人的复杂性。

    如果您真的想让它工作并且不关心按值传递字符串/语言环境,您可以将 trim 包装如下:

    int trim2(std::string s, const std::locale loc)
    {
      boost::trim<std::string>(s, loc);
      return 0;
    }
    

    然后做:

    std::for_each(df.colnames.begin(), df.colnames.end(),
        std::bind2nd(std::ptr_fun(trim2), std::locale()));
    

    P.S: (1) 可能依赖于库。我刚用 g++ 试过,返回 void 没有问题。

    【讨论】:

      猜你喜欢
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      相关资源
      最近更新 更多