c++模板參數——數值類型推斷


模板類中,或模板函數中,若限定模板參數為數值類型,可以使用如下方式進行判斷.

1 template<typename T>
2 Fmt::Fmt(const char *fmt, T val)
3 {
4     static_assert(std::is_arithmetic<T>::value != 0, "Must be arithmetic type");
5 
6     //length_ = snprintf(buf_, sizeof buf_, fmt, val);
7     //assert(static_cast<size_t>(length_) < sizeof buf_);
8 }

以上代碼節選自muduo.

其中主要推斷方式是通過調用std::is_arithmetic<T>.

若 T 為算術類型(即整數類型或浮點類型)或其修飾類型(添加注入const等),則提供等於 true 的成員常量 value 。對於任何其他類型, value為 false 。

 

示例代碼:

 1 #include <iostream>
 2 #include <type_traits>
 3  
 4 class A {};
 5  
 6 int main() 
 7 {
 8     std::cout << std::boolalpha;
 9     std::cout << "A:           " <<  std::is_arithmetic<A>::value << '\n';
10     std::cout << "bool:        " <<  std::is_arithmetic<bool>::value << '\n';
11     std::cout << "int:         " <<  std::is_arithmetic<int>::value << '\n';
12     std::cout << "int const:   " <<  std::is_arithmetic<int const>::value << '\n';
13     std::cout << "int &:       " <<  std::is_arithmetic<int&>::value << '\n';
14     std::cout << "int *:       " <<  std::is_arithmetic<int*>::value << '\n';
15     std::cout << "float:       " <<  std::is_arithmetic<float>::value << '\n';
16     std::cout << "float const: " <<  std::is_arithmetic<float const>::value << '\n';
17     std::cout << "float &:     " <<  std::is_arithmetic<float&>::value << '\n';
18     std::cout << "float *:     " <<  std::is_arithmetic<float*>::value << '\n';
19     std::cout << "char:        " <<  std::is_arithmetic<char>::value << '\n';
20     std::cout << "char const:  " <<  std::is_arithmetic<char const>::value << '\n';
21     std::cout << "char &:      " <<  std::is_arithmetic<char&>::value << '\n';
22     std::cout << "char *:      " <<  std::is_arithmetic<char*>::value << '\n';
23 }

運行結果:

 1 A:           false
 2 bool:        true
 3 int:         true
 4 int const:   true
 5 int &:       false
 6 int *:       false
 7 float:       true
 8 float const: true
 9 float &:     false
10 float *:     false
11 char:        true
12 char const:  true
13 char &:      false
14 char *:      false

 

PS:

std::is_integral<T> //檢查模板參數是否為整形
std::is_flotaing_point<T> //檢查模板參數是否為浮點數類型

 

PS:

如果您覺得我的文章對您有幫助,可以掃碼領取下紅包,謝謝!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM