変数のプレースホルダー型としての decltype と auto の違いは何ですか? 質問する

変数のプレースホルダー型としての decltype と auto の違いは何ですか? 質問する

私の理解では、両方ともdecltypeauto何かのタイプが何であるかを把握しようとします。

次のように定義します。

int foo () {
    return 34;
}

両方の宣言は合法です:

auto x = foo();
cout << x << endl;

decltype(foo()) y = 13;
decltype(auto)  y = 13; // alternatively, since C++14
cout << y << endl;

decltypeとの主な違いを教えてくださいauto

ベストアンサー1

decltype与える宣言した渡される式の型。autoテンプレートの型推論と同じことを行います。たとえば、参照を返す関数がある場合、はauto値のままですが (auto&参照を取得する必要があります)、decltype戻り値の型とまったく同じになります。

#include <iostream>
int global{};

int& foo()
{
   return global;
}
 
int main()
{
    decltype(foo()) a = foo(); //a is an `int&`
 // decltype(auto)  a = foo();   alternatively, since C++14

    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&`
 // decltype(auto)  c = foo();   alternatively, since C++14
    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"
 }

または のいずれか一方のみが可能な場合については、David Rodríguez の回答も参照してautoくださいdecltype

おすすめ記事