请看下面的代码
#include <iostream>
#include <functional>
#include <string>
int main()
{
std::function<void(std::string&)> theFunc;
std::string foo = "0";
theFunc = [](std::string a) { a = "1"; }; // this compiles but has a different function signature
theFunc(foo);
std::cout << "foo should be 1 but is " << foo << std::endl;
theFunc = [](auto a) { a = "2"; }; // this infers the wrong type for auto(by val not by ref), creates the wrong function signature and compiles
theFunc(foo);
std::cout << "foo should be 2 but is " << foo << std::endl;
theFunc = [](std::string& a) { a = "3"; }; // this compiles and correctly manipulates the string
theFunc(foo);
std::cout << "foo should be 3 and is " << foo << std::endl;
theFunc = [](auto& a) { a = "4"; }; // this compiles and correctly manipulates the string
theFunc(foo);
std::cout << "foo should be 4 and is " << foo << std::endl;
std::cin.get();
}
在代码示例中,我们有一个 std::function 分配了不同类型的 lambda。
我理解 lambda 3 因为函数签名匹配。
但是 lambda 1 创建了不同的函数签名,但编译正确。
Lambda 2 推断出错误的自动类型(通过 val 而不是通过 ref)并正确编译。
这是功能还是错误?我对函数类/ lambdas 和自动类型推断有什么误解?
更新:
感谢Handy999的回答,但是为什么以下内容没有编译呢?
std::function<void(std::string)> theFunc2;
theFunc2 = [](std::string& a) { a = "1"; }; // this doesn't compile and has a different function signature
theFunc2(foo);