获取没有显式特征的整数模板参数的有符号/无符号变体

发布于 2024-09-01 21:14:02 字数 912 浏览 4 评论 0原文

我希望定义一个模板类,其模板参数始终是整数类型。该类将包含两个成员,一个是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九局 2024-09-08 21:14:02

答案在 中。

要确定类型的有符号性,请使用 std::is_signedstd::is_unsigned

对于添加/删除签名,有 std::make_signedstd::make_unsigned

The answer is in <type_traits>

For determining the signed-ness of a type use std::is_signed and std::is_unsigned.

For adding/removing signed-ness, there is std::make_signed and std::make_unsigned.

神也荒唐 2024-09-08 21:14:02

如果您不能或不想依赖 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文