如何对具有带符号数字类型的事物进行谓词

How to predicate on something having a signed numeric type?

本文关键字:谓词 类型 数字 带符号      更新时间:2023-10-16

假设我有一些模板化的代码,它执行以下操作:

T x = foo();
T y = -x;

现在,如果T是非数字类型(或者没有实现一元减号),编译就会失败。但如果它是一个无符号的int、无符号的short等,它将成功,并发出警告。所以我希望能够做

T x = foo();
if (/* magic condition */ {
    T y = -x;
}

我可以写表达式来表达T的类型是某种有符号数字类型的条件吗?例如使用typeid?

注意:

  • 断言也很好,但我想要更灵活的东西

C++11具有is_unsigned特性,可以在static_assert:中使用

#include <type_traits>
template <typename T>
void foo()
{
    static_assert(std::is_unsigned<T>::value);
    T x = /* ... */
    T y = -x;
    /* ... */
}

如果你需要更动态的检查,那么就把它放在if条件下:

template <typename T>
void foo()
{
    if (!std::is_unsigned<T>::value) {
        /* To arrive here and for the following
           not to error out, we must have a numeric
           type that's not unsigned! */
        T x = /* ... */
        T y = -x;
    }
    else {
       /* Do something else for unsigned numeric
          types */
    }
}

更复杂的解决方案涉及重载、std::enable_if和各种其他模板元黑客,但以上可能就是您所需要的。

可以。

static_assert(std::is_unsigned<T>::value, "Not unsigned!");  

(你需要包含type_traits才能工作。)

然后,您可以自然地调整编译过程,即使使用enable_if,如果您确信没有其他方法:)。