C++模板SFINAE特性與反射機(jī)制

C++模板提供了一個SFINAE(subsitate failure is not an error)的機(jī)制(模板匹配失敗不是錯誤),這是模板里面一個非常有意思的特性,利用這個機(jī)制可以檢查一個結(jié)構(gòu)體是否包含某個成員等操作。c++語言本身沒有提供反射機(jī)制(也有利用pb實現(xiàn)反射),利用SFINAE機(jī)制,可以實現(xiàn)類似于反射的功能。


在介紹SFINAE之前,整理一下模板的基本語法。

  • 基本語法
    C++模板基本的使用方法,使用關(guān)鍵字template, typename,可以實現(xiàn)基本泛型函數(shù)或者類。這里就不在贅述了。
// 一個簡單的函數(shù)模板例子
template<typename T>
T get_max(T a, T b)
{
    cout << "FUNCTION NAME : " << __FUNCTION__ << ", LINE : " <<__LINE__ << endl;
    cout << a << " " << b << endl;
    auto result = a > b ? a: b;
    return result;
}

// 提供特化版本,處理某些特定類型
template<>
float get_max(float a, float b)
{
    cout << "FUNCTION NAME : " << __FUNCTION__ << ", LINE : " <<__LINE__ << endl;
    cout << "float : " << a << " " << b << endl;
    auto result = a > b ? a: b;
    return result;
}

// 提供偏特化版本,解決傳遞指針的問題
template<typename T>
T get_max(T* a, T* b)
{
    cout << "FUNCTION NAME : " << __FUNCTION__ << ", LINE : " <<__LINE__ << endl;
    cout << *a << " " << *b << endl;
    auto result = *a > *b ? *a: *b;
    return result;
}

// 默認(rèn)值模板
template<typename T = std::string>
T get_max(string a, string b)  // 默認(rèn)值這里的參數(shù)類型需要直接指定
{
    cout << "FUNCTION NAME : " << __FUNCTION__ << ", LINE : " <<__LINE__ << endl;
    cout << "STRING : " <<a << " " << b << endl;
    return a;
}
  • 關(guān)鍵字decltype的用法
    1)尾置返回類型
    通過decltype指定模板函數(shù)的返回類型
// 尾置返回類型
template<typename T1, typename T2>
auto get_max(T1 a, T2 b) -> decltype(b < a ? a : b)
{
    cout << "FUNCTION NAME : " << __FUNCTION__ << ", LINE : " <<__LINE__ << endl;
    cout << a << " " << b << endl;
    return a > b ? a: b;
}

2)獲得變量的類型

int a=8, b=3;
auto c = a + b;  //運(yùn)行時需要實際執(zhí)行a+b,哪怕編譯時就能推導(dǎo)出類型
decltype(a+b) d; //編譯期類型推導(dǎo)
// auto c;  // error // 不可以用auto c; 直接聲明變量,必須同時初始化。
  • 模板匹配decay機(jī)制
    模板在進(jìn)行匹配的時候,會進(jìn)行一個退化,比如const int 如果找不到對應(yīng)的類型,會退化為int。其實就是把各種引用啊什么的修飾去掉,把cosnt int&退化為int。
// 模板類型退化 decay 
template<typename T>
T get_max_decay(T a, T b)
{
    cout << "FUNCTION NAME : " << __FUNCTION__ << ", LINE : " <<__LINE__ << endl;
    return a > b ? a: b;
}

int main()
{
    // 模板類型退化 decay 
    // 看著比較抽象,其實就是把各種引用啊什么的修飾去掉,把cosnt int&退化為int
    int const c = 42;
    int i = 1;
    get_max_decay(i, c); // OK: T 被推斷為 int,c 中的 const 被 decay 掉
    get_max_decay(c, c); // OK: T 被推斷為 int

    int& ir = i;
    get_max_decay(i, ir); // OK: T 被推斷為 int, ir 中的引用被 decay 掉

    // ...
}
  • SFINAE 機(jī)制
    SFINAE(Substitution Failure Is Not An Error,替換失敗并非錯誤)這個看著很抽象,實際非常簡單,是一種常見的模板技巧。比如,利用模板的SFINAE判斷一個結(jié)構(gòu)體中是否包含某個成員。
#include <iostream>
#include <type_traits>
using namespace std;

template<typename T>
struct check_has_member_id
{
    // 僅當(dāng)T是一個類類型時,“U::*”才是存在的,從而這個泛型函數(shù)的實例化才是可行的
    // 否則,就將觸發(fā)SFINAE
    template<typename U>
    static void check(decltype(&U::id)){}

    // // 僅當(dāng)觸發(fā)SFINAE時,編譯器才會“被迫”選擇這個版本
    template<typename U>
    static int check(...){}

    enum {value = std::is_void<decltype(check<T>(NULL))>::value};
};

struct TEST_STRUCT
{
    int rid;
};

struct TEST_STRUCT2
{
    int id;
};

int main()
{
    check_has_member_id<TEST_STRUCT> t1;
    cout << t1.value << endl;

    check_has_member_id<TEST_STRUCT2> t2;
    cout << t2.value << endl;

    check_has_member_id<int> t3;
    cout << t3.value << endl;
    return 0;
}
// g++ --std=c++11  xxx.c

核心的代碼是在實例化check_has_member_id對象的時候,通過模板參數(shù)T的類型,決定了結(jié)構(gòu)體中對象value的值。而value的值是通過check<T>函數(shù)的返回值是否是void決定的。如果T中含有id成員的話,那么就會匹配第一個實例,返回void;如果不包含id的話,會匹配默認(rèn)的實例,返回int。

利用這個機(jī)制還可以做很多類似的判斷,比如判斷一個類是否是結(jié)構(gòu)體。

#include <iostream>
#include <type_traits>

// 2. 判斷變量是否是一個struct 或者 類
// http://www.itdecent.cn/p/d09373b83f86
template <typename T>
struct check
{
    template <typename U>
    static void check_class(int U::*) {}

    template <typename U>
    static int check_class(...) {}

    enum { value = std::is_void<decltype(check_class<T>(0))>::value };
};

class myclass {};

int main()
{
    check<myclass> t;
    std::cout << t.value << std::endl;

    check<int> t2;
    std::cout << t2.value << std::endl;
    return 0;
}
  • enable_if 語法

如果T是一個int類型,那么返回值是bool類型。如果不是int的話,就匹配不到找個實例。使用enable_if的好處是控制函數(shù)只接受某些類型的(value==true)的參數(shù),否則編譯報錯。

// 判斷class T 是否有某個成員函數(shù)
// enable if 
// enable_if example: two ways of using enable_if
#include <iostream>
#include <type_traits>

// 1. the return type (bool) is only valid if T is an integral type:
template <class T>
typename std::enable_if<std::is_integral<T>::value,bool>::type
  is_odd (T i) {return bool(i%2);}

int main() 
{
    short int i = 1;    // code does not compile if type of i is not integral
    std::cout << "i is odd: " << is_odd(i) << std::endl;

    // 編譯錯誤
    // double j = 10.0;
    // std::cout << "i is odd: " << is_odd(j) << std::endl;

    return 0;
}

利用模板的這種機(jī)制,可以設(shè)計“通用”函數(shù)接口。比如,如果work_func<T>(T data) 函數(shù)傳入的類型T中包含了T::is_print成員就打印“xxxx”,如果不包含就打印“yyy”。


這個事情除了可以用模板來做,利用反射也可以實現(xiàn)。c++本身沒有提供反射,利用pb,也可以實現(xiàn)。下面介紹一下基于pb實現(xiàn)的c++反射的機(jī)制。

int get_feature(const HeartBeatMessage& hb_msg, const std::string& name) 
{
    const google::protobuf::Descriptor* des = hb_msg.GetDescriptor();
    const google::protobuf::FieldDescriptor* fdes = des->FindFieldByName(name);
    assert(fdes != nullptr);
    const google::protobuf::Reflection* ref = hb_msg.GetReflection();
    cout << ref->GetString(hb_msg, fdes) << endl;
    return 0;
}

int main()
{
    HeartBeatMessage msg;
    fstream input("./heartbeat.db",ios::in|ios::binary);
    if(!msg.ParseFromIstream(&input))
    {
        cerr << "read data from file error." << endl;
        return -1;
    }
    
    // msg 是pb的msg對象,從msg對象里面找到對應(yīng)“hostname”字段 
    get_feature(msg, "hostName");
}

todo ...


參考:
https://jguegant.github.io/blogs/tech/sfinae-introduction.html
https://my.oschina.net/u/4051725/blog/4458011
https://izualzhy.cn/SFINAE-and-enable_if

stackoverflow上面有很多大佬balalala寫了很多,延伸閱讀:
https://stackoverflow.com/questions/257288/templated-check-for-the-existence-of-a-class-member-function

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 夜鶯2517閱讀 128,103評論 1 9
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,822評論 28 54
  • 兔子雖然是枚小碩 但學(xué)校的碩士四人寢不夠 就被分到了博士樓里 兩人一間 在學(xué)校的最西邊 靠山 兔子的室友身體不好 ...
    待業(yè)的兔子閱讀 2,765評論 2 9
  • 信任包括信任自己和信任他人 很多時候,很多事情,失敗、遺憾、錯過,源于不自信,不信任他人 覺得自己做不成,別人做不...
    吳氵晃閱讀 6,361評論 4 8

友情鏈接更多精彩內(nèi)容