經常使用Macro

enable_ifide

  SFINAE是英文Substitution failure is not an error的縮寫. 這句話什麼意思呢?當調用模板函數時編譯器會根據傳入參數推導最合適的模板函數,在這個推導過程當中若是某一個或者某幾個模板函數推導出來是編譯沒法經過的,只要有一個能夠正確推導出來,那麼那幾個推導獲得的可能產生編譯錯誤的模板函數並不會引起編譯錯誤。函數

struct Test {
    typedef int foo;
};

template <typename T> 
void f(typename T::foo) {} // Definition #1

template <typename T> 
void f(T) {}               // Definition #2

int main() {
    f<Test>(10); // Call #1.
    f<int>(10);  // Call #2. Without error (even though there is no int::foo) thanks to SFINAE.
}

  這是wiki上SFINAE的一個經典示例,註釋已經解釋的至關明白,因爲推導模板函數過程當中能夠找到一個正確的版本,因此即時int::foo是一個語法錯誤,可是編譯器也不會報錯。這就是SFINAE要義。在C++11中,標準確立了這種編譯的行爲spa

  enable_if 的實現:scala

  

  看一下應用。3d

  

  下在是更爲經常使用的應用,用於區分函數的實現:code

  

  std::enable_if的運用使這兩個函數的返回值在同一個函數調用的推導過程當中只有一個合法,遵循SFINAE原則,則能夠順利經過編譯。看一下調用:blog

  

 

參考:https://www.jianshu.com/p/a961c35910d2get

std::is_trivial編譯器

  If T is TrivialType (that is, a scalar type, a trivially copyable class with a trivial default constructor, or array of such type/class, possibly cv-qualified), provides the member constant value equal true. For any other type, value is false.string

  數值類型::value 爲true,不然 ::value爲false

 

  Helper variable template

  

參考:https://en.cppreference.com/w/cpp/types/is_trivial

std::tie

  tie 有兩個功能。

一、pack成一個 tuple,因此能夠用於快速比較。以下:

struct S {
    int n;
    std::string s;
    float d;
    bool operator<(const S& rhs) const
    {
        // compares n to rhs.n,
        // then s to rhs.s,
        // then d to rhs.d
        return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);
    }
};

二、能夠用於 unpack tuple、pair

int main()
{
    std::set<S> set_of_s; // S is LessThanComparable
 
    S value{42, "Test", 3.14};
    std::set<S>::iterator iter;
    bool inserted;
 
    // unpacks the return value of insert into iter and inserted
    std::tie(iter, inserted) = set_of_s.insert(value);
 
    if (inserted)
        std::cout << "Value was inserted successfully\n";
}

參考:

一、https://en.cppreference.com/w/cpp/utility/tuple/tie

相關文章
相關標籤/搜索