如何预测具有签名数字类型的东西?

ein*_*ica 4 c++ polymorphism typeof conditional-compilation typeid

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

T x = foo();
T y = -x;
Run Code Online (Sandbox Code Playgroud)

现在,如果T是非数字类型(或者没有实现一元减号),则编译将失败.但如果它是unsigned int,unsigned short等,它会成功,并带有警告.所以我希望能够做到

T x = foo();
if (/* magic condition */ {
    T y = -x;
}
Run Code Online (Sandbox Code Playgroud)

我可以写明文条件 - 在编译时或运行时检查 - T的类型是一些有符号的数字类型?例如使用typeid?

注意:

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

Lig*_*ica 6

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;

    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

如果您需要检查更具动态性,那么只需将其粘贴在一个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 */
    }
}
Run Code Online (Sandbox Code Playgroud)

更复杂的解决方案涉及重载,std::enable_if以及各种其他模板metahackery,但上述可能就是您所需要的.