考虑以下代码:
#include <iostream>
#include <functional>
// passing function object by value
void foo(std::function<int(int, int)> f) {
std::cout << f(3, 7) << std::endl;
}
// passing const function object by reference
void bar(const std::function<int(int, int)> & f) {
std::cout << f(3, 7) << std::endl;
}
// passing non-const function object by reference
void fizz(std::function<int(int, int)> & f) {
std::cout << f(3, 7) << std::endl;
}
int main() {
std::function<int(int, int)> g1 = [] (int x, int y) { return x * y; };
auto g2 = [] (int x, int y) { return x * y; };
foo(g1); // OK
foo(g2); // OK
bar(g1); // OK
bar(g2); // OK
fizz(g1); // OK
// compile error:
// error: invalid initialization of reference of type
// 'std::function<int(int, int)>&' from expression of type
// 'main()::<lambda(int, int)>'
// error: in passing argument 1 of 'void fizz(std::function<int(int, int)>&)'
fizz(g2);
}
有人可以向我解释一下:
(a) 为什么fizz(g2)
会产生编译错误,而其他构造不会?如果我在声明中明确键入它的类型,似乎可以通过引用传递一个 lambda,但如果我使用auto
关键字,或者如果我将函数参数类型声明为const
.
(b)这里的函数参数类型是什么意思? const
(C)在什么情况下我更喜欢按值传递而不是引用(更新:现在是一个单独的问题:C++11:通过引用或值传递(lambda 或其他)函数对象?)?
感谢您的任何见解。