当我包含< limits>时,有什么区别?或< limits.h>在我的C ++代码中 [英] What difference does it make when I include <limits> or <limits.h> in my c++ code
问题描述
有人可以解释一下吗?
#include <iostream>
#include <limits.h>
或
#include <iostream>
#include <limits>
推荐答案
<limits>
是C ++标准库标头提供与C标头<limits.h>
类似的见解(在C ++中也可以作为 <climits>
),但是它的编写方式在C ++程序中更加有用和安全:
<limits>
is a C++ Standard Library header providing similar insights to the C header <limits.h>
(which is also available in C++ as <climits>
), but it is written in a way that's more useful and safe in C++ programs:
-
假设您有一个
template <typename Numeric> ...
,并且内部代码想知道用户实例化模板所使用的Numeric
类型参数的最小值和最大值:您可以使用std::numeric_limits<Numeric>::min()
和;如果要从 <climits>
访问相同的值,则很难知道要使用SCHAR_MIN
,SHRT_MIN
,INT_MIN
,LONG_MIN
等中的哪个,并且必须在它们之间进行切换所有人-如此琐碎的事情有很多额外的代码
say you have a
template <typename Numeric> ...
, and the code inside wants to know the minimum and maximum value of theNumeric
type parameter that the user instantiated your template with: you can usestd::numeric_limits<Numeric>::min()
and...::max()
; if you wanted to access the same values from<climits>
, it'd be hard to know which ofSCHAR_MIN
,SHRT_MIN
,INT_MIN
,LONG_MIN
etc. to use and you'd have to switch between them all yourself - lots of extra code for something so trivial
<climits>
有很多宏,并且宏不像常规" C ++标识符那样尊重名称空间或范围-它们的替换非常随意-因此它们使您的程序更容易出错
<climits>
has lots of macros, and macros don't respect namespaces or scopes the way "normal" C++ identifiers do - their substitutions are made pretty indescriminately - so they make your program more error prone
<limits>
提供了有关数字类型的更多信息,例如它们是否带符号,它们可以处理的以10为基数的数字,是否可以表示无穷大或无数字的定点值等. .(有关完整列表和信息,请参见标题文档)
<limits>
gives much more insight about numeric types, such as whether they're signed, the number of base-10 digits they can handle, whether they can represent infinity or not-a-number sentinel values etc. (see the header docs for a fuller list and information)
这篇关于当我包含< limits>时,有什么区别?或< limits.h>在我的C ++代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!