2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++: decltypeとは

Last updated at Posted at 2025-12-20

decltype(デクルタイプ)とは

C++11で採用された機能。
オペランドで指定した式の型を取得する。

decltypelvalue / rvalueも考慮する。

変数での使用

decltype(i) j = 0;  // j はiの型
decltype(i)* p = &i;  // p はi*型
decltype((i)) r = i;  // r はi&型

decltype((i))iが式として評価(lvalue)され参照型となる。

関数の戻り値として使用

template<typename T, typename U>
auto add(const T& l, const U& r)
    -> decltype(l + r);  // addの戻り値の型は`l + r`

decltype(auto)

C++14から
decltypeに与える式を右辺の式で置き換えて型推論する機能

decltype(auto) d = a + b;  // `auto`がa + bで置き換えられる。

関数の戻り値として使用

template<typename T>
decltype(auto) f(T& r){
    return r;  // T&が戻り値型に 
}

autoとの違い

autoは値から推論する(参照、constなどが落ちる)
decltypeは式自体を推論する(参照、constがそのまま)

int x;
int y = &x;

auto z = y;  // int型
decltype(auto) b = rx;  // int&型

参考文献

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?