是否可以将运算符传递给lambda?例如,将某些运算符传递给以下功能。
auto lambdaCompare = [](value,compare1,compare2,op){return value op compare1 and value op compare2;};
答案 0 :(得分:5)
您不能传递运算符然后随意使用它,但是可以传递std::greater_equal
:
#include <iostream>
#include <functional>
int main() {
auto lambdaCompare = [](int value, int compare1, int compare2, std::function<bool(int, int)> op) {
return op(value, compare1) && op(value, compare2);
};
std::cout << lambdaCompare(2, 1, 6, std::greater_equal<int>());
return 0;
}
答案 1 :(得分:3)
auto l = [](auto value, auto c1, auto c2, auto op)
{
return (op(value, c1) && op(value, c2));
};
l(1, 2, 3, [](int a, int b) { return a < b; });
auto l = [](int value, int c1, int c2, bool(* op)(int, int))
{
return (op(value, c1) && op(value, c2));
};
l(1, 2, 3, [](int a, int b) { return a < b; });
我是否真的建议这样做有矛盾。一方面,这是一个宏大的,另一方面,它看起来很无辜,这是简单而又不言自明的
auto l = [](auto value, auto c1, auto c2, auto op)
{
return (op(value, c1) && op(value, c2));
};
l(1, 2, 3, OPERATOR(<));
l(1, 2, 3, OPERATOR(<=));
l(1, 2, 3, OPERATOR(>));
l(1, 2, 3, OPERATOR(>=));
l(1, 2, 3, OPERATOR(==));
l(1, 2, 3, OPERATOR(!=));
使用
#define OPERATOR(op) [] (const auto& a, const auto& b) { return a op b; }
auto l = [](int value, int c1, int c2, Op_t<int, int, bool> op)
{
return (op(value, c1) && op(value, c2));
};
l(1, 2, 3, OPERATOR(int, int, <));
l(1, 2, 3, OPERATOR(int, int, <=));
l(1, 2, 3, OPERATOR(int, int, >));
l(1, 2, 3, OPERATOR(int, int, >=));
l(1, 2, 3, OPERATOR(int, int, ==));
l(1, 2, 3, OPERATOR(int, int, !=));
使用
#define OPERATOR(T1, T2, op) [] (const T1& a, const T2& b) { return a op b; }
template <class T1, class T2, class R>
using Op_t = auto (*) (const T1&, const T2&) -> R;
答案 2 :(得分:2)
如果您的运算符是自由函数,则您可能会回退到类似
的状态struct S
{
public:
S(int i) : i (i) {}
int i;
};
bool operator < (const S& s1, const S& s2)
{
return s1.i < s2.i;
}
int main()
{
auto lambda_compare = [](S s1, S s2, auto op) {
return op(s1, s2);
};
bool b = lambda_compare(S(1), S(2), operator<);
return 0;
}