C++中如何判断整数类型是否为内置类型
判断整数类型是否为内置类型的实现方案
分为C++和C两种语言场景,均为编译期判断,无运行时开销,可以直接在程序逻辑中使用。
C++ 实现
基于标准库<type_traits>的类型匹配实现,支持所有C++标准版本:
#include <type_traits> template<typename T> constexpr bool is_builtin_integral_v = std::is_same_v<T, bool> || std::is_same_v<T, char> || std::is_same_v<T, signed char> || std::is_same_v<T, unsigned char> || std::is_same_v<T, short> || std::is_same_v<T, unsigned short> || std::is_same_v<T, int> || std::is_same_v<T, unsigned int> || std::is_same_v<T, long> || std::is_same_v<T, unsigned long> || std::is_same_v<T, long long> || std::is_same_v<T, unsigned long long> || std::is_same_v<T, wchar_t> || std::is_same_v<T, char8_t> || // C++20及以上支持 std::is_same_v<T, char16_t> || std::is_same_v<T, char32_t>;
使用示例:
static_assert(is_builtin_integral_v<int> == true); static_assert(is_builtin_integral_v<__int128> == false); // 编译器扩展类型返回false
C 实现
基于C11引入的_Generic泛型选择实现,编译期即可得到结果:
#include <stdbool.h> #define is_builtin_integral(T) _Generic((T){0}, \ bool: true, \ char: true, \ signed char: true, \ unsigned char: true, \ short: true, \ unsigned short: true, \ int: true, \ unsigned int: true, \ long: true, \ unsigned long: true, \ long long: true, \ unsigned long long: true, \ default: false)
使用示例:
_Static_assert(is_builtin_integral(int) == 1, "int是内置类型"); _Static_assert(is_builtin_integral(__int128) == 0, "__int128不是标准内置类型");
说明
- 上述实现覆盖了C/C++标准规定的所有内置整数类型,编译器自定义的扩展整数类型(如
int128系列)不会被匹配,符合需求。 - 所有判断逻辑完全在编译期完成,无任何运行时开销,可直接用于静态断言、编译期分支选择等场景。
- 如果需要适配特定编译器的特殊内置类型,直接在对应的匹配列表中添加对应类型即可。
内容的提问来源于stack exchange,提问作者zhanglistar
相关产品推荐
相关产品推荐

