当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c++模板参数——数值类型推断

c++模板参数——数值类型推断

2018年11月05日  | 移动技术网IT编程  | 我要评论

伊莲菲,电子爱好者,7个月的胎儿

模板类中,或模板函数中,若限定模板参数为数值类型,可以使用如下方式进行判断.

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:

如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢!

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网