autoキーワードC++のautoキーワードは、C++11で導入された強力な機能で、型を推論して変数を宣言するために使います。
コンパイラーが初期化子をもとに変数の型を推論するので、コードが読みやすく、保守しやすくなります。
autoを使って変数を宣言する、次の例を見てみましょう。
auto dragon_population{3}; // dragon_population is deduced as an integer
auto westeros{7.7777}; // westeros is deduced as a double
auto wedding_location{"The Twins"}; // wedding_location is deduced as a const char*, not std::string
いずれの場合も、変数の型は初期化に使った値から推論されます。
autoキーワードは、明示的な型を書く手間を減らしてくれるので、より簡潔で読みやすいコードを書く助けになります。
const std::vector<std::string> pigeon_pie{"flour", "butter", "pigeon", "salt"};
auto purple_wedding_pie{pigeon_pie};
purple_wedding_pie.emplace_back("the strangler");
このコードでは、autoがpurple_wedding_pieの型をstd::vector<std::string>と推論してくれるので、同じ型をもう一度明示する必要がありません。
autoキーワードはさまざまなC++の構文と組み合わせて使えるので、現代のC++プログラミングでは汎用性の高い道具になります。
auto& element{array[0]}; // reference to an element
const auto object{otherObject}; // const type version of otherObject's type
auto* ptr{&x}; // pointer to x with the same type as x, but as a pointer.
この後のコンセプトでは、ラムダ式や範囲ベースのforループ、イテレーターと一緒にautoキーワードを使う場面をよく見ることになります。
autoが特に役立ちます。autoを使うとコードがすっきりし、保守しやすくなります。