c++ - 重载所有基本整数类型是否足以捕获所有整数?

标签 c++ c++11 language-lawyer

假设我有所有标准整数类型的函数重载:

void foo( char );
void foo( signed char );
void foo( short );
void foo( int );
void foo( long );
void foo( long long );
// .... all unsigned variants as well

这些重载是否有可能无法为诸如 int8_t 之类的类型找到合适的重载?是否有一种可移植的方法来处理此类过载?

引用怎么样?

澄清问题:来自对这个问题的讨论 Why is int8_t read as a character?并声称可能存在编译器生成的整数类型,这些整数类型不是基本 C++ 类型的别名。因此,在这种情况下,所有基本情况的重载可能不会接受。另一方面,我无法为 int8_t 提供重载,因为在许多平台上它只是一个别名,并且会在重新定义现有重载时出错。

最佳答案

该标准不保证标准整数类型是编译器支持的唯一整数类型。事实上,C 和 C++ 标准明确允许编译器定义其他整数类型,统称为“扩展整数类型”:

There may also be implementation-defined extended signed integer types.

Likewise, for each of the extended signed integer types there exists a corresponding extended unsigned integer type ...

the extended signed integer types and extended unsigned integer types are collectively called the extended integer types.

并且 C 标准不禁止实现使用扩展整数类型来实现 stdint.h 类型。甚至还有这种非规范的表示法,只是为了说清楚:

Some of these types may denote implementation-defined extended integer types.

如果您想要一个可以采用任何整数类型的函数,您有两个选择:将其设为模板(可能使用 SFINAE 来禁止非整数类型)或提供一个采用 std::intmax_t。该标准要求 intmax_t 是支持的最大整数:

designates a signed integer type capable of representing any value of any signed integer type

当然,“有符号整数类型”包括标准类型和扩展类型。所以 std::intmax_t 可以处理实现支持的任何有符号整数。

关于c++ - 重载所有基本整数类型是否足以捕获所有整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41552514/

相关文章:

c++ - 如何构建用于分发的 SDL C++ 程序?

c++ - Boost.PropertyTree子路径处理

c++ - 是否有 GCC pragma 来打开和关闭 C++11?

c++ - 同样的 clang ,std::initializer_list 程序与 -std=c++14/-std=c++17 的结果不同

c++ - 越界访问数组,但返回较早 - UB?

c++ - 选择什么库来为使用 SDL 的 C++ 软件构建用户界面

c++ - 这段代码有什么问题?

c++ - 可以在主体中调用 C++ 中的委托(delegate)构造函数还是仅在初始化列表中调用?

c++ - 作为另一个函数参数的函数调用是否遵循任何定义的行为?

c - &((struct name *)NULL -> b) 会导致 C11 中的未定义行为吗?