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 == 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);
关于c++ - std::bind 占位符的重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11347730/