最近發現了一個有意思的特性:void_t。
void_t是C++17引入的一個新特性,它的定義很簡單(有些編譯器的實現可能不是這樣,但也大體類似):
template< class... > using void_t = void;
看著它很簡單,但它搭配SFINAE卻可以在模板元編程中發揮巨大作用。
比如在編譯期判斷類是否有某個類型using:
template> struct has_type : std::false_type {}; template struct has_type > : std::true_type {};
比如判斷是否有某個成員:
template> struct has_a_member : std::false_type {}; template struct has_a_member ().a)>> : std::true_type {};
比如判斷某個類是否可迭代:
templateconstexpr bool is_iterable{}; template constexpr bool is_iterable ().begin()), decltype(std::declval ().end())>> = true;
比如判斷某個類是否有某個函數:
templatestruct has_hello_func : std::false_type {}; template struct has_hello_func ().hello())>> : std::true_type {};
測試結果:
struct HasType {
typedef int type;
};
struct NHasType {
int hello;
};
struct Hasa {
int a;
};
struct NHasa {
int b;
};
struct HasHello {
void hello();
};
struct NoHasHello {};
int main() {
std::cout << has_type::value << '
'; // 1
std::cout << has_type::value << '
'; // 0
std::cout << has_a_member::value << '
'; // 1
std::cout << has_a_member::value << '
'; // 0
std::cout << has_hello_func::value << '
'; // 1
std::cout << has_hello_func::value << '
'; // 0
std::cout << is_iterable> << '
'; // 1
std::cout << is_iterable << '
'; // 0
}
它的原理其實就是利用SFINAE和模板優先找特化去匹配的特性,估計大家應該看示例代碼就能明白。
審核編輯:劉清
聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。
舉報投訴
-
編譯器
+關注
關注
1文章
1672瀏覽量
51598 -
C++語言
+關注
關注
0文章
147瀏覽量
7682
原文標題:C++17一個很冷門很有意思的新特性
文章出處:【微信號:C語言編程,微信公眾號:C語言編程】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
相關推薦
熱點推薦
【設計技巧】rtos的核心原理簡析
rtos的核心原理簡析rtos全稱real-time operating system(實時操作系統),我來簡單分析下:我們都知道,c語句中調用一個
發表于 07-23 08:00
OpenHarmony智慧設備開發-芯片模組簡析T507
降噪,自動調色系統和梯形校正模塊可以提供提供流暢的用戶體驗和專業的視覺效果。
典型應用場景:
工業控制、智能駕艙、智慧家居、智慧電力、在線教育等。
、*附件:OpenHarmony智慧設備開發-芯片模組簡析T507.docx
發表于 05-11 16:34
a17和a16的參數區別
哪些重要的區別呢?本文將一一探討。 1. 內核改進 C++17引入了一些內核改進,其中最顯著的是對字符串的內存使用的優化。在C++16的版中,字符串引用傳遞時,會發生大量的無效副本拷貝
C++ invoke與function的區別在哪?
invoke是C++17標準引入的一個函數模板,用來調用可調用對象(Callable Object,如函數指針、函數對象、成員函數指針等)并返回結果。
C++17引入的一個新特性void_t簡析
評論