整数特征(is_integer、is_integral)
我需要两个关于整数的特征。
第一个类似于
std::is_integral
(或boost::is_integral
),但可与用户定义的类型一起使用(例如包装>int
,例如int_wrapper
):如果类型的行为类似于整数并且其表示形式类似于标准整数类型(例如sizeof(T) * CHAR_BITS == std:: numeric_limits
(如果::digits T
是无符号的))但是整型的定义非常严格,因为它由这些类型的列表组成。因此,如果不禁止的话,专门化std::is_integral
似乎很困难(尽管我认为没有明确说明):is_integral
是一个“主要”类型特征(20.7.4.1,注释 3) :对于类型 T 来说,只有一个主要类型特征为 true,在我的例子中,int_wrapper
已经is_class
等于 true)。 如果我将此特征专门用于int_wrapper
,我会承担哪些风险? 您知道适合我的需求的特征类(例如在 Boost 中)吗?我需要的第二个特征是具有整数语义的类型(具有位算术运算、位操作等)。例如,GMP 中的
mpz_class
将满足此特征。std::numeric_limits
适合此特征吗?我读到,如果::is_integer T
的行为像整数,则可以专门化和设置numeric_limits
,而且(在 C++ 标准中)术语“integral”和“integer”是同义词(在这种情况下,我们应该总是有::is_integer == true numeric_limits
)::is_integer == is_integral ::value
总之,我更好吗是根据我的具体需求定义自己的特征,还是尝试扩展标准特征?
I need two traits concerning integers.
The first one would be like
std::is_integral
(orboost::is_integral
), but usable with user defined types (for example a class wrapping anint
, sayint_wrapper
): true if the type behaves like an integer and whose representation is like standard integral types (e.g.sizeof(T) * CHAR_BITS == std::numeric_limits<T>::digits
ifT
is unsigned) But the definition of an integral type is very rigid, in that it consists of a list of these types. So specializingstd::is_integral
seems difficult, if not forbidden (though not stated explicitly I think):is_integral
is a "primary" type trait (20.7.4.1, note 3: exactly one primary type trait is true for a type T, in my caseint_wrapper
has alreadyis_class
equal to true).
What are the risks I take if I specialize this trait forint_wrapper
?
Do you know of a trait class (e.g. in Boost) that fit my needs?The second trait I need is for types having integer semantics (with bits arithmetic operations, bit manipulations etc.). For example the
mpz_class
from GMP would satisfy this trait. Isstd::numeric_limits<T>::is_integer
appropriate for this trait? I read both that it is OK to specialize and setnumeric_limits<T>::is_integer == true
ifT
behaves like an integer, but also (in the C++ standard) that the terms "integral" and "integer" are synonymous (in which case we sould always havenumeric_limits<T>::is_integer == is_integral<T>::value
)
In conclusion, am I better of defining my own traits for my precise needs, or try extending standard ones?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于您是否希望 boost 和其他标准库将您的类视为不可或缺的部分。如果是这样,你别无选择,只能专门化 std/boost::is_integral<> 。否则,请制作您自己的 is_integral<>其默认实现转发到 std/boost::is_integral<>并将其专门用于您的整体包装。
It depends whether you want boost and other standard libraries to treat your class as integral. If so, you have no other way but specialize std/boost::is_integral<>. Otherwise make your own is_integral<> with its default implementation forwarding to std/boost::is_integral<> and specialize it for your integral wrapper.