私が理解しているように、両方ともdecltype
、auto
何かのタイプが何であるかを理解しようとします。
定義すると:
int foo () {
return 34;
}
その場合、両方の宣言は合法です。
auto x = foo();
cout << x << endl;
decltype(foo()) y = 13;
cout << y << endl;
decltype
との主な違いを教えてくださいauto
。
私が理解しているように、両方ともdecltype
、auto
何かのタイプが何であるかを理解しようとします。
定義すると:
int foo () {
return 34;
}
その場合、両方の宣言は合法です。
auto x = foo();
cout << x << endl;
decltype(foo()) y = 13;
cout << y << endl;
decltype
との主な違いを教えてくださいauto
。
decltype
渡される式の宣言されたタイプを示します。auto
テンプレートタイプの推論と同じことを行います。したがって、たとえば、参照を返す関数がある場合、それでも値になります(参照を取得するauto
必要があります)が、正確には戻り値の型になります。auto&
decltype
#include <iostream>
int global{};
int& foo()
{
return global;
}
int main()
{
decltype(foo()) a = foo(); //a is an `int&`
auto b = foo(); //b is an `int`
b = 2;
std::cout << "a: " << a << '\n'; //prints "a: 0"
std::cout << "b: " << b << '\n'; //prints "b: 2"
std::cout << "---\n";
decltype(foo()) c = foo(); //c is an `int&`
c = 10;
std::cout << "a: " << a << '\n'; //prints "a: 10"
std::cout << "b: " << b << '\n'; //prints "b: 2"
std::cout << "c: " << c << '\n'; //prints "c: 10"
}
auto
また、1つだけまたは可能である場所についてのDavidRodríguezの回答も参照してくださいdecltype
。
auto
(型を推測するコンテキストでは)初期化子が存在する変数の型を定義することに限定されます。decltype
は、追加情報を犠牲にして、式のタイプを推測する、より広範な構成です。
使用できる場合は、型を推測する式を指定する必要がないため、auto
よりも簡潔です。decltype
auto x = foo(); // more concise than `decltype(foo()) x`
std::vector<decltype(foo())> v{ foo() }; // cannot use `auto`
このキーワードauto
は、関数の末尾の戻り型を使用する場合、まったく関係のないコンテキストでも使用されます。
auto foo() -> int;
リーダーのみが存在auto
するため、コンパイラーは、これが末尾の戻り型を持つ宣言であることを認識します。上記の例は簡単に古いスタイルに変換できますが、ジェネリックプログラミングでは次のようになります。
template <typename T, typename U>
auto sum( T t, U u ) -> decltype(t+u)
この場合、auto
はリターンタイプの定義には使用できないことに注意してください。
@Mankarseのサンプルコードを変更してください。
#include <iostream>
int global = 0;
int& foo()
{
return global;
}
int main()
{
decltype(foo()) a = foo(); //a is an `int&`
auto b = foo(); //b is an `int`
b = 2;
std::cout << "a: " << a << '\n'; //prints "a: 0"
std::cout << "b: " << b << '\n'; //prints "b: 2"
std::cout << "global: " << global << '\n'; //prints "global: 0"
std::cout << "---\n";
//a is an `int&`
a = 10;
std::cout << "a: " << a << '\n'; //prints "a: 10"
std::cout << "b: " << b << '\n'; //prints "b: 2"
std::cout << "global: " << global << '\n'; //prints "global: 10"
return 0;
}
一般に、初期化する変数の型が必要な場合は、autoを使用します。decltypeは、戻り型など、変数ではないものの型が必要な場合に適しています。
autoは純粋に単純化された機能であると思いますが、decltypeの主な目的は、基盤ライブラリで高度なメタプログラミングを可能にすることです。ただし、言語技術の使用の観点から見ると、これらは非常に密接に関連しています。
HOPL20 4.2.1から、BjarneStroustrup。