C 判斷某個類是否有某個成員函式,如果有則呼叫

2021-10-11 06:21:07 字數 1560 閱讀 7126

有兩個sdk版本,a版本類base有setscalingmode函式,b版本類base無setscalingmode函式, 為了同時相容兩個sdk版本,共用一套**,常見的是通過巨集隔離,但版本眾多時管理起來會很麻煩,若可先判斷是否含有該函式,若有則呼叫,c++11新增特性解決了這一問題

//偽**

// 如果支援setscalingmode

if(hassetscalingmode())

匹配失敗不是錯誤。就是說,匹配過載的函式 / 類時如果匹配後會引發編譯錯誤,這個函式 / 類就不會作為候選(不會報錯)。這是乙個 c++11 的新特性,也是 enable_if 最核心的原理,其作用是當我們在進行模板特化的時候,會去選擇那個正確的模板

推導表示式的型別,但不會執行表示式

int i;

double t;

struct a ;

const a* a = new a();

decltype(a) x1; //x1 是 a*

decltype(i) x2; //x2 是 int

decltype(a -> x) x3; // x3 是 double

不管是否有預設建構函式或該型別不可以建立物件。(可以用於抽象基類); 

templatebool ckhassetscalingmode(decltype(std::declval().setscalingmode(std::declval())) *test = nullptr)

templatebool ckhassetscalingmode(...)

呼叫方式

ckhassetscalingmode(nullptr)

templatestruct hasset

; 使用方式

hasset::value

templateint b2hgbp(...) ;

template int b2hgbp(t *t, int mode) ;

//該方案需先識別是含有該函式

/*templateint b2hgbp(typename std::enable_if::value, t>::type *t, int mode) ;*/

定義如下,只有第乙個引數為true時才會定義type,enable_if::type即為t,而enable_if::type會引發編譯錯誤

// primary template.

/// define a member typedef @c type only if a boolean constant is true.

templatestruct enable_if

;// partial specialization for true.

templatestruct enable_if;

sfinae 

enable_if  

c 11判斷某個類是否具有某個函式成員

by 鳥哥 c 11判斷某個類是否含有某個成員函式和變數 include include include template typename t struct has member f1 template typename t struct has member aa struct class1 v...

檢查類中是否有某個成員函式

1.檢查類中是否有成員函式,不包括繼承的成員函式 例子1 templatestruct has no destroy 例子2 templatestruct has foo 2.檢查類中是否有成員函式,包括繼承的成員函式 template class has foo class no struct b...

在C 中判斷某個類是否實現了某個介面

有時我們需要判斷某個類是否實現了某個介面 inte ce 比如在使用反射機制 reflection 來查詢特定型別的時候。簡單來說,可以使用type.isassignablefrom方法 1 2 typeof ifoo isassignablefrom bar.gettype typeof ifoo...