c++ - std::bind 占位符的重载运算符

标签 c++ boost stl operator-overloading bind

boost::bind为其占位符重载多个运算符:

For convenience, the function objects produced by bind overload the logical not operator ! and the relational and logical operators ==, !=, <, <=, >, >=, &&, ||.

例如,这允许我通过 _1 == desired_value作为 STL 算法的谓词。

不幸的是,std::bind似乎没有使这些运算符重载:(

  1. 这是为什么?

  2. 什么是模拟 _1 == desired_value 的好方法?与 std::bind ?

最佳答案

IIRC,Boost.Bind 仅重载占位符的那些运算符,因为 Boost.Bind 是其改进的原始 Boost Lambda 库(Boost.Bind 已过时,多亏了 Boost.Phoenix,顺便说一句)。 std::bind 的占位符仅用于此目的,作为 std::bind 的参数的占位符。

作为解决方法,使用多态仿函数:

struct compare_equal{
  template<class LHS, class RHS>
  bool operator()(LHS&& lhs, RHS&& rhs){ // assume bool return
    return std::forward<LHS>(lhs) == std::forward<RHS>(rhs);
  }
};

// ...
auto bound = std::bind(compare_equal(), _1, desired_value);

Live example on Ideone.

关于c++ - std::bind 占位符的重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11347730/

相关文章:

c++ - 如何重定向 cout 和 cin?

c++ - 为 std::regex_match 使用自定义分配器

c++ - 检查 Gdiplus::Bitmap::FromFile 是否返回了有效的位图

C++:vector 中的 shared_ptr 没有更新原始的 shared_ptr

c++ - X代码 6 : Unable to create watchpoint

c++ - boost 转换产生 Inf 返回值

c++ - 如何从程序中删除日志调试语句

c++ - boost python链接

c++ - 如何通过多个键索引和查询 STL 映射容器?

c++ - vector::iterator 和 set::iterator 的原理区别