次のコードを見てください
#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();
}
コード例では、異なるタイプのラムダが割り当てられた 1 つの std::function があります。
関数の署名が一致するため、ラムダ 3 は理解できます。
ただし、ラムダ 1 は別の関数シグネチャを作成しますが、正しくコンパイルされます。
Lambda 2 は (ref ではなく val によって) 間違った auto 型を推測し、正しくコンパイルします。
これは機能ですか、それともバグですか? 関数クラス/ラムダと自動型推論に関して、私は何を誤解していますか?
アップデート:
回答 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);