经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
c++模板参数——数值类型推断
来源:cnblogs  作者:从此寂静无声  时间:2018/11/5 11:09:46  对本文有异议

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

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

以上代码节选自muduo.

其中主要推断方式是通过调用std::is_arithmetic<T>.

若 T 为算术类型(即整数类型或浮点类型)或其修饰类型(添加注入const等),则提供等于 true 的成员常量 value 。对于任何其他类型, value为 false 。

 

示例代码:

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

运行结果:

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

 

PS:

std::is_integral<T> //检查模板参数是否为整形
std::is_flotaing_point<T> //检查模板参数是否为浮点数类型

 

PS:

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

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号