std::numeric_limits<T>::max

来自cppreference.com
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
 
 
在标头 <limits> 定义
static T max() throw();
(C++11 前)
static constexpr T max() noexcept;
(C++11 起)

返回数值类型 T 所能表示的最大有限值。对所有有界类型都有意义。

返回值

T std::numeric_limits<T>::max()
/* 未特化 */ T()
bool true
char CHAR_MAX
signed char SCHAR_MAX
unsigned char UCHAR_MAX
wchar_t WCHAR_MAX
char8_t (C++20 起) UCHAR_MAX
char16_t (C++11 起) UINT_LEAST16_MAX
char32_t (C++11 起) UINT_LEAST32_MAX
short SHRT_MAX
unsigned short USHRT_MAX
int INT_MAX
unsigned int UINT_MAX
long LONG_MAX
unsigned long ULONG_MAX
long long (C++11 起) LLONG_MAX
unsigned long long (C++11 起) ULLONG_MAX
float FLT_MAX
double DBL_MAX
long double LDBL_MAX

示例

演示在一些基本类型和一些标准库的 typedef 上使用 max()(输出是系统限定的):

#include <cstddef>
#include <iostream>
#include <limits>
#include <string_view>
#include <type_traits>
 
template<typename T>
void print_max_twice(std::string_view type)
{
    constexpr T max_value {std::numeric_limits<T>::max()};
 
    std::cout << type << ": ";
    if constexpr (std::is_floating_point_v<T>)
        std::cout << std::defaultfloat << max_value << " 或 "
                  << std::hexfloat << max_value << '\n';
    else
        std::cout << std::dec << static_cast<unsigned long long>(max_value) << " 或 "
                  << std::hex << static_cast<unsigned long long>(max_value) << '\n';
}
 
int main()
{
    std::cout << std::showbase;
 
    print_max_twice<bool>("bool");
    print_max_twice<short>("short");
    print_max_twice<int>("int");
    print_max_twice<std::streamsize>("streamsize");
    print_max_twice<std::size_t>("size_t");
    print_max_twice<char>("char");
    print_max_twice<char16_t>("char16_t");
    print_max_twice<wchar_t>("wchar_t");
    print_max_twice<float>("float");
    print_max_twice<double>("double");
    print_max_twice<long double>("long double");
}

可能的输出:

bool: 1 或 0x1
short:32767 或 0x7fff
int:2147483647 或 0x7fffffff
streamsize:9223372036854775807 或 0x7fffffffffffffff
size_t:18446744073709551615 或 0xffffffffffffffff
char: 127 或 0x7f
char16_t: 65535 或 0xffff
wchar_t: 2147483647 或 0x7fffffff
float:3.40282e+38 或 0x1.fffffep+127
double:1.79769e+308 或 0x1.fffffffffffffp+1023
long double:1.18973e+4932 或 0xf.fffffffffffffffp+16380

参阅

[静态] (C++11)
返回给定类型的最低有限值
(公开静态成员函数)
[静态]
返回给定类型的最小有限值
(公开静态成员函数)