日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++?Boost?EnableIf函數使用介紹_C 語言

作者:無水先生 ? 更新時間: 2022-12-16 編程語言

一、說明

Boost.EnableIf

Boost.Enable If 可以禁用重載函數模板或專用類模板。禁用意味著編譯器忽略相應的模板。這有助于防止出現模棱兩可的情況,即編譯器不知道要使用哪個重載函數模板。它還可以更輕松地定義不僅可用于特定類型而且可用于一組類型的模板。

從 C++11 開始,Boost.EnableIf 已經成為標準庫的一部分。您可以在不使用 Boost 庫的情況下調用本章介紹的函數;只需包含頭文件 type_traits。

二、Boost.EnableIf的示例

示例 49.1。在返回值上使用 boost::enable_if 重載函數

#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';
}

Example49.1

示例 49.1 定義了函數模板 create(),它返回作為模板參數傳遞的類型的對象。該對象在 create() 中初始化,不接受任何參數。兩個 create() 函數的簽名沒有區別。在這方面,create() 不是重載函數。如果 Boost.EnableIf 沒有啟用一個函數而禁用另一個,編譯器將報告錯誤。

Boost.EnableIf 提供類 boost::enable_if,這是一個需要兩個參數的模板。第一個參數是條件。如果條件為真,第二個參數是 boost::enable_if 表達式的類型。訣竅在于,如果條件為假,則此類型不存在,在這種情況下,boost::enable_if 表達式是無效的 C++ 代碼。然而,當涉及到模板時,編譯器不會抱怨無效代碼。相反,它會忽略模板并搜索另一個可能適合的模板。這個概念被稱為 SFINAE,它代表“替換失敗不是錯誤”。

在示例 49.1 中,boost::enable_if 表達式中的兩個條件都使用類 std::is_same。此類在 C++11 標準庫中定義,允許您比較兩種類型。因為這樣的比較不是真就是假,所以使用 std::is_same 來定義條件就足夠了。

如果條件為真,相應的 create() 函數應返回作為模板參數傳遞給 create() 的類型的對象。這就是 T 作為第二個參數傳遞給 boost::enable_if 的原因。如果條件為真,則整個 boost::enable_if 表達式將替換為 T。在示例 49.1 中,編譯器會看到返回 int 的函數或返回 std::string 的函數。如果使用 int 或 std::string 以外的任何其他類型調用 create(),編譯器將報告錯誤。

示例 49.1 顯示提升。

示例 49.2。使用 boost::enable_if 為一組類型專門化函數

#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);
}

Example49.2

示例 49.2 使用 boost::enable_if 為一組類型特化一個函數。該函數稱為 print() 并需要一個參數。它可以被重載,盡管重載要求您使用具體類型。要對一組類型(如 short、int 或 long)執行相同的操作,您可以使用 boost::enable_if 定義適當的條件。示例 49.2 使用 std::is_integral 來做到這一點。第二個 print() 函數為所有浮點數重載了 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>();
}

原文鏈接:https://yamagota.blog.csdn.net/article/details/127945003

欄目分類
最近更新