获取整型模板参数的有符号/无符号变量,无需显式traits [英] Get the signed/unsigned variant of an integer template parameter without explicit traits
问题描述
我想要定义一个模板类,其模板参数将始终是一个整数类型。类将包含两个成员,一个类型 T
,另一个作为 T
类型的无符号变量 - 即if T == int
,然后 T_Unsigned == unsigned int
。我的第一本能是这样做:
I am looking to define a template class whose template parameter will always be an integer type. The class will contain two members, one of type T
, and the other as the unsigned variant of type T
-- i.e. if T == int
, then T_Unsigned == unsigned int
. My first instinct was to do this:
template <typename T> class Range {
typedef unsigned T T_Unsigned; // does not compile
public:
Range(T min, T_Unsigned range);
private:
T m_min;
T_Unsigned m_range;
};
但它不工作。然后我考虑使用部分模板专门化,像这样:
But it doesn't work. I then thought about using partial template specialization, like so:
template <typename T> struct UnsignedType {}; // deliberately empty
template <> struct UnsignedType<int> {
typedef unsigned int Type;
};
template <typename T> class Range {
typedef UnsignedType<T>::Type T_Unsigned;
/* ... */
};
只要你部分专门化 UnsignedType
每个整数类型。这是一个额外的复制粘贴工作(斜线明智的使用宏),但可服务。
This works, so long as you partially specialize UnsignedType
for every integer type. It's a little bit of additional copy-paste work (slash judicious use of macros), but serviceable.
但是,我现在好奇 - 是否有另一种方法来确定整数类型的有符号类型,和/或使用类型的无符号变量,而不必手动定义每个类型的Traits类?
However, I'm now curious - is there another way of determining the signed-ness of an integer type, and/or using the unsigned variant of a type, without having to manually define a Traits class per-type? Or is this the only way to do it?
推荐答案
答案在< type_traits>
要确定类型的签名类型,请使用std :: is_signed和std :: is_unsigned
For determining the signed-ness of a type use std::is_signed and std::is_unsigned
对于添加/删除签名,有std :: make_signed和std :: make_unsigned
For adding/removing signed-ness, there is std::make_signed and std::make_unsigned
这篇关于获取整型模板参数的有符号/无符号变量,无需显式traits的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!