zoukankan      html  css  js  c++  java
  • 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 << '
    ';
    10     std::cout << "bool:        " <<  std::is_arithmetic<bool>::value << '
    ';
    11     std::cout << "int:         " <<  std::is_arithmetic<int>::value << '
    ';
    12     std::cout << "int const:   " <<  std::is_arithmetic<int const>::value << '
    ';
    13     std::cout << "int &:       " <<  std::is_arithmetic<int&>::value << '
    ';
    14     std::cout << "int *:       " <<  std::is_arithmetic<int*>::value << '
    ';
    15     std::cout << "float:       " <<  std::is_arithmetic<float>::value << '
    ';
    16     std::cout << "float const: " <<  std::is_arithmetic<float const>::value << '
    ';
    17     std::cout << "float &:     " <<  std::is_arithmetic<float&>::value << '
    ';
    18     std::cout << "float *:     " <<  std::is_arithmetic<float*>::value << '
    ';
    19     std::cout << "char:        " <<  std::is_arithmetic<char>::value << '
    ';
    20     std::cout << "char const:  " <<  std::is_arithmetic<char const>::value << '
    ';
    21     std::cout << "char &:      " <<  std::is_arithmetic<char&>::value << '
    ';
    22     std::cout << "char *:      " <<  std::is_arithmetic<char*>::value << '
    ';
    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:

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

  • 相关阅读:
    青春三部曲(《且听风吟》,《一九七三年的弹子球》,《寻羊冒险记》)--[日]村上春树
    《假如给我三天光明》--[美]海伦·凯勒
    《老人与海》--[美]欧内斯特·米勒尔·海明威
    《曾国藩发迹史》--汪衍振
    《挪威的森林》--[日]村上春树
    《海边的卡夫卡》--[日]村上春树
    你也可以用java的swing可以做出这么炫的mp3播放器_源码下载
    你用java的swing可以做出这么炫的mp3播放器吗?
    《罗密欧与朱丽叶》--[英]莎士比亚
    《肖申克的救赎》--[美]斯蒂芬·金
  • 原文地址:https://www.cnblogs.com/jason1990/p/9902105.html
Copyright © 2011-2022 走看看