You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在编译时验证用户自定义字面量输入并检测数值溢出?

实现自定义字面量的编译时溢出检查

要在自定义字面量_asInt中实现编译时的数值范围检查,确保unsigned long long转换为int时不会溢出,可以借助constexpr和static_assert来实现,具体修改如下:

首先需要包含<limits>头文件以使用std::numeric_limits获取int的取值范围,然后在自定义字面量运算符中添加编译时断言:

#include <cassert>
#include <limits> // 必须包含这个头文件

constexpr int operator "" _asInt(unsigned long long i) {
    // 编译时检查i是否在int的取值范围内
    static_assert(i <= std::numeric_limits<int>::max(), 
                  "Literal value exceeds int's maximum limit");
    return static_cast<int>(i);  
}

int main() {
  int a = 1_asInt; // 正常编译,无警告/错误
  int b = 99999999999999999_asInt; // 触发编译错误,提示超出范围
  int c = 99999999999999999; // 编译器原生警告
}

关键说明:

  • static_assert是编译时断言,只有当条件不满足时才会触发编译错误,完全匹配你需要的编译时检查需求。
  • 自定义字面量的参数i是编译期常量(字面量本身就是编译时确定的),因此可以直接在static_assert中使用。
  • 由于参数是unsigned long long类型,只需检查是否小于等于int的最大值即可,无需考虑负数边界。

如果你的编译器支持C++20及以上标准,还可以使用std::cmp_less_equal来规避潜在的类型转换问题,但上述写法已能满足基础需求。

内容的提问来源于stack exchange,提问作者sji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:10:28