获取没有显式特征的整数模板参数的有符号/无符号变体
我希望定义一个模板类,其模板参数始终是整数类型。该类将包含两个成员,一个是 T
类型,另一个是 T
类型的无符号变体 - 即如果 T == int
>,然后T_Unsigned == unsigned int
。我的第一直觉是这样做:
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;
};
但这不起作用。然后我考虑使用部分模板特化,如下所示:
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
,这种方法就有效。这是一些额外的复制粘贴工作(明智地使用宏),但是有用。
但是,我现在很好奇 - 是否有另一种方法可以确定整数类型的有符号性,和/或使用类型的无符号变体,而无需为每个类型手动定义 Traits 类?或者这是唯一的方法?
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;
/* ... */
};
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案在
中。要确定类型的有符号性,请使用
std::is_signed
和std::is_unsigned
。对于添加/删除签名,有
std::make_signed
和std::make_unsigned
。The answer is in
<type_traits>
For determining the signed-ness of a type use
std::is_signed
andstd::is_unsigned
.For adding/removing signed-ness, there is
std::make_signed
andstd::make_unsigned
.如果您不能或不想依赖 TR1/C++0x 功能,Boost.TypeTraits 还为您提供
make_unsigned
等。If you can't or don't want to depend on TR1/C++0x features, Boost.TypeTraits also offers you
make_unsigned<>
et al.