2015-09-14 34 views
2

给定函数工作:为什么汽车不能与某些lambda表达式

void foo(std::function<void(int, std::uint32_t, unsigned int)>& f) 
{ 
    f(1, 2, 4); 
} 

为什么这个编译:

std::function<void(int a, std::uint32_t b, unsigned int c)> f = 
    [] (int a, std::uint32_t b, unsigned int c) -> void 
{ 
    std::cout << a << b << c << '\n'; 
    return; 
}; 

这无法编译:

auto f = 
    [] (int a, std::uint32_t b, unsigned int c) -> void 
{ 
    std::cout << a << b << c << '\n'; 
    return; 
}; 

与错误:

5: error: no matching function for call to 'foo' 
    foo(f); 
    ^~~ 
6: note: candidate function not viable: no known conversion from '(lambda at...:9)' to 'std::function<void (int, std::uint32_t, unsigned int)> &' for 1st argument 
void foo(std::function<void(int, std::uint32_t, unsigned int)>& f) 
    ^
+0

您是否试过使用不同的编译器?尝试使用clang和gcc是个好主意。 – user1095108

+0

可能的重复:https://stackoverflow.com/questions/1565600 –

回答

13

拉姆达不是std::function。因此,调用foo函数需要从lambda中构建临时对象std::function,并将此临时值作为参数传递。但foo函数需要std::function类型的可修改左值。显然,一个临时值不能被非const左值引用所约束。以为例改为:

void foo(std::function<void(int, std::uint32_t, unsigned int)> f) 
{ 
    f(1, 2, 4); 
} 
+2

通过'const&'捕获应该也能工作,对吧? –

+0

@dau_sama:是的 –

相关问题