std::is_arithmetic

来自cppreference.com
< cpp‎ | types
 
 
元编程库
类型特征
类型类别
(C++11)
(C++14)  
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
is_arithmetic
(C++11)
类型属性
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(C++20 前*)
(C++11)(C++20 中弃用)
(C++11)
类型特征常量
元函数
(C++17)
受支持操作
关系与属性查询
类型修改
(C++11)(C++11)(C++11)
类型变换
(C++11)(C++23 中弃用)
(C++11)(C++23 中弃用)
(C++11)
(C++11)
(C++17)

(C++11)(C++20 前*)(C++17)
编译时有理数算术
编译时整数序列
 
在标头 <type_traits> 定义
template< class T >
struct is_arithmetic;
(C++11 起)

std::is_arithmetic一元类型特征 (UnaryTypeTrait)

如果 T 为算术类型(即整数类型或浮点类型)或其 cv 限定版本,那么提供的成员常量 value 等于 true。对于其它任何类型,value 等于 false

如果程序添加了 std::is_arithmeticstd::is_arithmetic_v (C++17 起) 的特化,那么行为未定义。

模板形参

T - 要检查的类型

辅助变量模板

template< class T >
inline constexpr bool is_arithmetic_v = is_arithmetic<T>::value;
(C++17 起)

继承自 std::integral_constant

成员常量

value
[静态]
如果 T 为算术类型那么是 true,否则是 false
(公开静态成员常量)

成员函数

operator bool
将对象转换到 bool,返回 value
(公开成员函数)
operator()
(C++14)
返回 value
(公开成员函数)

成员类型

类型 定义
value_type bool
type std::integral_constant<bool, value>

注解

算术类型是定义了算术运算符+-*/)的内建类型(可能与一般算术转换结合)。

为所有算术类型都提供了 std::numeric_limits 的特化。

可能的实现

template<class T>
struct is_arithmetic : std::integral_constant<bool,
                                              std::is_integral<T>::value ||
                                              std::is_floating_point<T>::value> {};

示例

#include <atomic>
#include <cstddef>
#include <type_traits>
 
class A {};
 
enum class B : int { e };
 
static_assert(
    std::is_arithmetic_v<bool>            == true  and
    std::is_arithmetic_v<char>            == true  and
    std::is_arithmetic_v<char const>      == true  and
    std::is_arithmetic_v<int>             == true  and
    std::is_arithmetic_v<int const>       == true  and
    std::is_arithmetic_v<float>           == true  and
    std::is_arithmetic_v<float const>     == true  and
    std::is_arithmetic_v<std::size_t>     == true  and
 
    std::is_arithmetic_v<char&>           == false and
    std::is_arithmetic_v<char*>           == false and
    std::is_arithmetic_v<int&>            == false and
    std::is_arithmetic_v<int*>            == false and
    std::is_arithmetic_v<float&>          == false and
    std::is_arithmetic_v<float*>          == false and
    std::is_arithmetic_v<A>               == false and
    std::is_arithmetic_v<B>               == false and
    std::is_arithmetic_v<decltype(B::e)>  == false and
    std::is_arithmetic_v<std::byte>       == false and
    std::is_arithmetic_v<std::atomic_int> == false
);
 
int main() {}

参阅

检查类型是否为整数类型
(类模板)
检查类型是否是浮点类型
(类模板)