boost 或 STL 是否有用于比较两个 char 值的谓词?

Does boost or STL have a predicate for comparing two char values?

我需要在单个 char 值上调用 boost::trim_left_if

// pseudo code; not tested.
std::string to_trim{"hello"};
char left_char = 'h';
boost::algorithm::trim_left_if(to_trim, /*left_char?*/);

在上面的最后一行中,我需要一种方法来传递 char 值。我环顾四周,但没有看到 Boost 或 STL 中的通用谓词可以简单地比较两个任意值。我可以为此使用 lambda,但我更喜欢谓词,如果存在的话。

我想在这里避免的一件事是使用 boost::is_any_of() 或任何其他需要将 left_char 转换为字符串的谓词。

自 C++11 起,比较固定值是否相等的惯用方法是使用具有 std::equal_to:

的绑定表达式
boost::algorithm::trim_left_if(to_trim,
    std::bind(std::equal_to<>{}, left_char, std::placeholders::_1));

这使用透明谓词 std::equal_to<void> (C++14 起);在 C++11 中使用 std::equal_to<char>.

在 C++11 之前(很可能在 C++17 之前),您可以使用 std::bind1st 代替 std::bindstd::placeholders::_1.

保留在 Boost 中,您还可以使用具有单一范围的 boost::algorithm::is_any_of;我发现 boost::assign::list_of 效果很好:

boost::algorithm::trim_left_if(to_trim,
    boost::algorithm::is_any_of(boost::assign::list_of(left_char)));

为什么不写一个?

#include <iostream>
#include <boost/algorithm/string/trim.hpp>

struct Pred
{
    Pred(char ch) : ch_(ch) {}
    bool operator () ( char c ) const { return ch_ == c; }
    char ch_;
};

int main ()
{
    std::string to_trim{"hello"};
    char left_char = 'h';
    boost::algorithm::trim_left_if(to_trim, Pred(left_char));
    std::cout << to_trim << std::endl;
}

说真的 - boost 中的东西不是 "sent down from on high",它是由像你我这样的人写的。