最終更新日時(UTC):
が更新

履歴 編集

decltype(auto)(C++14)

概要

decltype(auto)は、decltypeに与える式を右辺の式で置き換えて型推論する機能である。

int a = 3;
int b = 2;

decltype(a + b) c = a + b; // cの型はint
decltype(auto)  d = a + b; // dの型もint。autoが式「a + b」で置き換えられる

参照の変数をautoキーワードで型推論した場合はTとなるが、decltype(auto)で型推論した場合はT&となる。

int x = 3;
int& r = x;

auto           a = r; // aの型はint
decltype(r)    b = r; // bの型はint&
decltype(auto) c = r; // cの型はint&

この機能は、通常関数の戻り値型推論の戻り値型プレースホルダーとしても使用できる:

// autoの場合はintが戻り値型となるが、
// decltype(auto)とすることでint&が戻り値型となる。
decltype(auto) f(int& r)
{
  return r;
}

#include <type_traits>

int main()
{
  int x = 3;
  int& r = x;

  auto           a = r; // aの型はint
  decltype(r)    b = r; // bの型はint&
  decltype(auto) c = r; // cの型はint&

  static_assert(std::is_same<decltype(a), int>::value, "");
  static_assert(std::is_same<decltype(b), int&>::value, "");
  static_assert(std::is_same<decltype(c), int&>::value, "");
}

出力

この機能が必要になった背景・経緯

decltype(auto)は、C++14で導入された「通常関数の戻り値型推論」の機能で、参照の変数を参照のままreturn文で返せるようにするために導入された。

関連項目