我在看似简单的代码中使用了 lambda:
#include <iostream>
#include <functional>
using my_type = unsigned int;
int main()
{
my_type def_val = -1;
auto correct_value = [&] (my_type &x, const my_type y, std::function<const my_type& (const my_type&, const my_type&)> selector)
{
if (x != def_val)
x = selector (x, y);
else
x = y;
};
my_type x = 10;
correct_value (x, 20, std::min<my_type>);
std::cout << x << std::endl;
return 0;
}
但它给出了一个编译错误:
main.cpp:18:5: error: no matching function for call to object of type '(lambda at main.cpp:10:22)'
correct_value (x, 20, std::min<my_type>);
^~~~~~~~~~~~~
main.cpp:10:22: note: candidate function not viable: no overload of 'min' matching 'std::function<const my_type &(const my_type &, const my_type &)>' (aka 'function<const unsigned int &(const unsigned int &, const unsigned int &)>') for 3rd argument
auto correct_value = [&] (my_type &x, const my_type y, std::function<const my_type& (const my_type&, const my_type&)> selector)
我做错了什么?似乎第三个参数(函数)对应于原型。但他还是骂。
在线编译器中的代码:tyk
准确告诉编译器您指的是哪个函数:
在线编译器中的代码:tyk。