std::void_t
來自 cppreference.com
定義於標頭檔案 <type_traits> |
||
template< class... > using void_t = void; |
(C++17 起) | |
將任意型別序列對映到 void 型別的元函式。在 C++20 的 概念 出現之前,這個元函式是利用 SFINAE 的便捷方式,特別是為了根據表示式在 未求值上下文 (例如 decltype 表示式的運算元) 中是否有效,有條件地從 候選集 中移除函式,從而允許根據支援的操作存在不同的函式過載或特化。
[編輯] 注意
這個元函式用於模板超程式設計中,以在 SFINAE 上下文中檢測格式錯誤的型別
// primary template handles types that have no nested ::type member: template<class, class = void> struct has_type_member : std::false_type {}; // specialization recognizes types that do have a nested ::type member: template<class T> struct has_type_member<T, std::void_t<typename T::type>> : std::true_type {};
它也可以用於檢測表示式的有效性
// primary template handles types that do not support pre-increment: template<class, class = void> struct has_pre_increment_member : std::false_type {}; // specialization recognizes types that do support pre-increment: template<class T> struct has_pre_increment_member<T, std::void_t<decltype( ++std::declval<T&>() )> > : std::true_type {};
在 CWG issue 1558 (一個 C++11 缺陷) 解決之前,別名模板 中未使用的引數不保證 SFINAE 並可能被忽略,因此早期的編譯器需要更復雜的 void_t
定義,例如
template<typename... Ts> struct make_void { typedef void type; }; template<typename... Ts> using void_t = typename make_void<Ts...>::type;
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_void_t |
201411L |
(C++17) | std::void_t
|
[編輯] 示例
執行此程式碼
#include <iomanip> #include <iostream> #include <map> #include <type_traits> #include <vector> // Variable template that checks if a type has begin() and end() member functions template<typename, typename = void> constexpr bool is_iterable = false; template<typename T> constexpr bool is_iterable< T, std::void_t<decltype(std::declval<T>().begin()), decltype(std::declval<T>().end()) > > = true; // An iterator trait those value_type is the value_type of the iterated container, // supports even back_insert_iterator (where value_type is void) template<typename T, typename = void> struct iterator_trait : std::iterator_traits<T> {}; template<typename T> struct iterator_trait<T, std::void_t<typename T::container_type>> : std::iterator_traits<typename T::container_type::iterator> {}; class A {}; #define SHOW(...) std::cout << std::setw(34) << #__VA_ARGS__ \ << " == " << __VA_ARGS__ << '\n' int main() { std::cout << std::boolalpha << std::left; SHOW(is_iterable<std::vector<double>>); SHOW(is_iterable<std::map<int, double>>); SHOW(is_iterable<double>); SHOW(is_iterable<A>); using container_t = std::vector<int>; container_t v; static_assert(std::is_same_v< container_t::value_type, iterator_trait<decltype(std::begin(v))>::value_type >); static_assert(std::is_same_v< container_t::value_type, iterator_trait<decltype(std::back_inserter(v))>::value_type >); }
輸出
is_iterable<std::vector<double>> == true is_iterable<std::map<int, double>> == true is_iterable<double> == false is_iterable<A> == false
[編輯] 參閱
(C++11) |
有條件地從過載解析中移除函式過載或模板特化 (類模板) |