std::variant_alternative, std::variant_alternative_t
來自 cppreference.com
< cpp | 工具庫 | 變體(variant)
定義於標頭檔案 <variant> |
||
template <std::size_t I, class T> struct variant_alternative; /* 未定義 */ |
(1) | (C++17 起) |
template <std::size_t I, class... Types> struct variant_alternative<I, variant<Types...>>; |
(2) | (C++17 起) |
template <std::size_t I, class T> class variant_alternative<I, const T>; |
(3) | (C++17 起) |
template <std::size_t I, class T> class variant_alternative<I, volatile T>; |
(3) | (C++17 起) (C++20 中已棄用) |
提供編譯時索引訪問,以獲取可能帶cv限定的變體(variant)的備選型別,它將變體的cv限定(如果有)與備選型別的cv限定組合起來。
形式上,
3) 滿足 TransformationTrait 要求,其成員 typedef
type
分別命名為 std::add_const_t<std::variant_alternative_t<I,T>>、std::add_volatile_t<std::variant_alternative_t<I,T>> 和 std::add_cv_t<std::variant_alternative_t<I,T>>目錄 |
[編輯] 成員型別
成員型別 | 定義 |
型別 | 變體的第 I 個備選型別,其中 I 必須在 [0, sizeof...(Types)) 範圍內,否則程式格式錯誤。 |
[編輯] 輔助模板別名
template <size_t I, class T> using variant_alternative_t = typename variant_alternative<I, T>::type; |
(C++17 起) | |
[編輯] 示例
執行此程式碼
#include <variant> #include <iostream> using my_variant = std::variant<int, float>; static_assert(std::is_same_v <int, std::variant_alternative_t<0, my_variant>>); static_assert(std::is_same_v <float, std::variant_alternative_t<1, my_variant>>); // cv-qualification on the variant type propagates to the extracted alternative type. static_assert(std::is_same_v <const int, std::variant_alternative_t<0, const my_variant>>); int main() { std::cout << "All static assertions passed.\n"; }
輸出
All static assertions passed.
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2974 | C++17 | 越界索引導致未定義行為 | 導致格式錯誤 |
[編輯] 參閱
(C++17) |
在編譯時獲取 `variant` 替代列表的大小 (類模板) (變數模板) |
獲取指定元素的型別 (類模板特化) |