C++ Boost EnableIf函數(shù)使用介紹
一、說明
Boost.EnableIf
Boost.Enable If 可以禁用重載函數(shù)模板或?qū)S妙惸0?。禁用意味著編譯器忽略相應的模板。這有助于防止出現(xiàn)模棱兩可的情況,即編譯器不知道要使用哪個重載函數(shù)模板。它還可以更輕松地定義不僅可用于特定類型而且可用于一組類型的模板。
從 C++11 開始,Boost.EnableIf 已經(jīng)成為標準庫的一部分。您可以在不使用 Boost 庫的情況下調(diào)用本章介紹的函數(shù);只需包含頭文件 type_traits。
二、Boost.EnableIf的示例
示例 49.1。在返回值上使用 boost::enable_if 重載函數(shù)
#include <boost/utility/enable_if.hpp> #include <type_traits> #include <string> #include <iostream> template <typename T> typename boost::enable_if<std::is_same<T, int>, T>::type create() { return 1; } template <typename T> typename boost::enable_if<std::is_same<T, std::string>, T>::type create() { return "Boost"; } int main() { std::cout << create<std::string>() << '\n'; }
示例 49.1 定義了函數(shù)模板 create(),它返回作為模板參數(shù)傳遞的類型的對象。該對象在 create() 中初始化,不接受任何參數(shù)。兩個 create() 函數(shù)的簽名沒有區(qū)別。在這方面,create() 不是重載函數(shù)。如果 Boost.EnableIf 沒有啟用一個函數(shù)而禁用另一個,編譯器將報告錯誤。
Boost.EnableIf 提供類 boost::enable_if,這是一個需要兩個參數(shù)的模板。第一個參數(shù)是條件。如果條件為真,第二個參數(shù)是 boost::enable_if 表達式的類型。訣竅在于,如果條件為假,則此類型不存在,在這種情況下,boost::enable_if 表達式是無效的 C++ 代碼。然而,當涉及到模板時,編譯器不會抱怨無效代碼。相反,它會忽略模板并搜索另一個可能適合的模板。這個概念被稱為 SFINAE,它代表“替換失敗不是錯誤”。
在示例 49.1 中,boost::enable_if 表達式中的兩個條件都使用類 std::is_same。此類在 C++11 標準庫中定義,允許您比較兩種類型。因為這樣的比較不是真就是假,所以使用 std::is_same 來定義條件就足夠了。
如果條件為真,相應的 create() 函數(shù)應返回作為模板參數(shù)傳遞給 create() 的類型的對象。這就是 T 作為第二個參數(shù)傳遞給 boost::enable_if 的原因。如果條件為真,則整個 boost::enable_if 表達式將替換為 T。在示例 49.1 中,編譯器會看到返回 int 的函數(shù)或返回 std::string 的函數(shù)。如果使用 int 或 std::string 以外的任何其他類型調(diào)用 create(),編譯器將報告錯誤。
示例 49.1 顯示提升。
示例 49.2。使用 boost::enable_if 為一組類型專門化函數(shù)
#include <boost/utility/enable_if.hpp> #include <type_traits> #include <iostream> template <typename T> void print(typename boost::enable_if<std::is_integral<T>, T>::type i) { std::cout << "Integral: " << i << '\n'; } template <typename T> void print(typename boost::enable_if<std::is_floating_point<T>, T>::type f) { std::cout << "Floating point: " << f << '\n'; } int main() { print<short>(1); print<long>(2); print<double>(3.14); }
示例 49.2 使用 boost::enable_if 為一組類型特化一個函數(shù)。該函數(shù)稱為 print() 并需要一個參數(shù)。它可以被重載,盡管重載要求您使用具體類型。要對一組類型(如 short、int 或 long)執(zhí)行相同的操作,您可以使用 boost::enable_if 定義適當?shù)臈l件。示例 49.2 使用 std::is_integral 來做到這一點。第二個 print() 函數(shù)為所有浮點數(shù)重載了 std::is_floating_point。
練習
使 print_has_post_increment() 寫入標準輸出,無論類型是否支持后增量運算符。例如,對于 int 程序應該輸出“int has a post increment operator”:
#include <string> template <class T> void print_has_post_increment() { // TODO: Implement this function. } int main() { print_has_post_increment<int>(); print_has_post_increment<long>(); print_has_post_increment<std::string>(); }
到此這篇關于C++ Boost EnableIf函數(shù)使用介紹的文章就介紹到這了,更多相關C++ Boost EnableIf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
c++中vector<int>和vector<int*>的用法及區(qū)別
這篇文章主要介紹了c++中vector<int>和vector<int*>的用法及區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2013-10-10