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

时间:2013-11-28 14:22:12

标签: c++ polymorphism conditional-compilation typeof typeid

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

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

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

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

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

注意:

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

2 个答案:

答案 0 :(得分: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;

    /* ... */
}

如果您需要检查更具动态性,请将其粘贴在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以及各种其他模板元共享,但上述内容可能就是您所需要的。

答案 1 :(得分:4)

是的,你可以。

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

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

如果您确定没有其他方法,您可以自然地调整编译过程,甚至可能使用enable_if