我应该使用 C 还是 C++返回变量类型的最大大小的实现?
从标准的角度来看,我应该使用 C++
标头中的以下内容吗?
UCHAR_MAX
这是 c 实现或 std::numeric_limits
这是 C++ 实现。
两个版本之间的结果是等效的,但在这种情况下我应该选择基于某些标准或可读性和可移植性的实现。请注意,此实现必须是跨平台兼容的。我正在编写 C++ 代码。
From a standards standpoint, should I use the following from the C++ <limits>
header?
UCHAR_MAX
which is the c implementation orstd::numeric_limits<unsigned char>::max()
which is the C++ implementation.
The result is equivalent between the two versions but should I choose an implementation based on some standard or on readability and portability in this case. Note this implementation must be cross-platform compatible. I am writing C++ code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您希望代码能够编译为 C,那么您非常需要使用
。如果您正在编写 C++,那么最好使用 C++
标头。后者允许您编写可在模板中运行的代码,这些代码实际上无法与 C 标头复制:If you want the code to be able to compile as C, then you pretty much need to use
<limits.h>
. If you're writing C++, it's probably better to use the C++<limits>
header instead. The latter lets you write code that will work in templates that can't really be duplicated with the C header:知道你用什么语言写作,然后用那种语言写作。如果您正在编写 C++,请使用标准 C++ 的处理方式。
标准 C++ 通常是跨平台兼容的(也有例外,例如
export
,但export
无论如何都会从 C++ 标准中删除)。坚持使用 C++ 结构通常比在 C 和 C++ 结构之间切换更具可读性。Know what language you're writing in, and write in that language. If you're writing C++, use the standard C++ ways of doing things.
Standard C++ is normally cross-platform compatible (there are exceptions, like
export
, butexport
is being removed from the C++ Standard anyway). It's usually more readable to stick with C++ constructs than to switch between C and C++ constructs.您应该使用保持一致。
在 Windows 平台上,如果包含,您可能还希望
避免与 min 和 max 发生名称冲突。
You should use <limits> to stay consistant.
On the windows platform, if you include <windows.h>, you might also want to
to avoid a name conflict with min and max.
当您使用 C 时,
std::numeric_limits
显然不可用。在 C++ 中,这取决于您想要执行的操作 -
std::numeric_limits::max()
不是当前 C++ 标准的常量表达式。在这些情况下,C-ish 宏的替代方法是使用 Boost.Integers 整数特征
const_min
/const_max
也适用于模板化上下文。When you are using C,
std::numeric_limits
obviously isn't available.In C++ it depends on what you want to do -
std::numeric_limits<T>::max()
is not a constant expression with the current C++ standard.In these cases an alternative to the C-ish macros would be to use something like Boost.Integers integer traits
const_min
/const_max
which also works in templated contexts.