std::unwrap_reference, std::unwrap_ref_decay
From cppreference.com
< cpp | utility | functional
| ヘッダ <type_traits> で定義 |
||
| ヘッダ <functional> で定義 |
||
| template< class T > struct unwrap_reference; |
(1) | (C++20以降) |
| template< class T > struct unwrap_ref_decay; |
(2) | (C++20以降) |
あらゆる std::reference_wrapper をアンラップします: std::reference_wrapper<U> を U& に変更します。
プログラムがこのページで説明されているテンプレートのいずれかに特殊化を追加する場合、動作は未定義です。
目次 |
[編集] 入れ子型
| 型 | 定義 |
type
|
(1) |
[編集] ヘルパー型
| template<class T> using unwrap_reference_t = unwrap_reference<T>::type; |
(1) | (C++20以降) |
| template<class T> using unwrap_ref_decay_t = unwrap_ref_decay<T>::type; |
(2) | (C++20以降) |
[編集] 実装例
template<class T> struct unwrap_reference { using type = T; }; template<class U> struct unwrap_reference<std::reference_wrapper<U>> { using type = U&; }; template<class T> struct unwrap_ref_decay : std::unwrap_reference<std::decay_t<T>> {}; |
[編集] 備考
std::unwrap_ref_decay は、std::make_pair および std::make_tuple で使用される変換と同じ変換を実行します。
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_unwrap_ref |
201811L |
(C++20) | std::unwrap_ref_decay と std::unwrap_reference |
[編集] 例
このコードを実行
#include <cassert> #include <functional> #include <iostream> #include <type_traits> int main() { static_assert(std::is_same_v<std::unwrap_reference_t<int>, int>); static_assert(std::is_same_v<std::unwrap_reference_t<const int>, const int>); static_assert(std::is_same_v<std::unwrap_reference_t<int&>, int&>); static_assert(std::is_same_v<std::unwrap_reference_t<int&&>, int&&>); static_assert(std::is_same_v<std::unwrap_reference_t<int*>, int*>); { using T = std::reference_wrapper<int>; using X = std::unwrap_reference_t<T>; static_assert(std::is_same_v<X, int&>); } { using T = std::reference_wrapper<int&>; using X = std::unwrap_reference_t<T>; static_assert(std::is_same_v<X, int&>); } static_assert(std::is_same_v<std::unwrap_ref_decay_t<int>, int>); static_assert(std::is_same_v<std::unwrap_ref_decay_t<const int>, int>); static_assert(std::is_same_v<std::unwrap_ref_decay_t<const int&>, int>); { using T = std::reference_wrapper<int&&>; using X = std::unwrap_ref_decay_t<T>; static_assert(std::is_same_v<X, int&>); } { auto reset = []<typename T>(T&& z) { // x = 0; // Error: does not work if T is reference_wrapper<> // converts T&& into T& for ordinary types // converts T&& into U& for reference_wrapper<U> decltype(auto) r = std::unwrap_reference_t<T>(z); std::cout << "r: " << r << '\n'; r = 0; // OK, r has reference type }; int x = 1; reset(x); assert(x == 0); int y = 2; reset(std::ref(y)); assert(y == 0); } }
出力
r: 1 r: 2
[編集] 関連項目
| (C++11) |
コピー構築可能 (CopyConstructible) かつ コピー代入可能 (CopyAssignable) な参照ラッパー (クラステンプレート) |
引数の型によって決定される型のpairオブジェクトを生成する(関数テンプレート) | |
| (C++11) |
引数型によって定義された型の tuple オブジェクトを生成する(関数テンプレート) |