模板元编程——g++ 吃掉了它,clang 没有

template metaprogramming - g++ eats it, clang does not

有什么方法可以让两个编译器都满意吗?

为此:

template<short value>
struct static_signbits
{
    enum { result = (!!(value & 0x8000) == !!(value & 0x4000)) ? (static_signbits<short(value << 1)>::result + 1) : 0 };
};

template<>
struct static_signbits<0>
{
    enum
    {
        result = 15
    };
};

clang 给我:

error: non-type template argument is not a constant expression
        enum { result = (!!(value & 0x8000) == !!(value & 0x4000)) ? (static_signbits<short(value << 1)>::result + 1) : 0 };
                                                                                      ^~~~~~~~~~~~~~~~~  

显然对短片的演员阵容不满意?

显然,我可以改用 constexpr,但我还需要向后兼容 C++98

这是因为clang不支持常量表达式中的negative << n。只需移动无符号值即可:

template<short value>
struct static_signbits
{
    enum { result = (!!(value & 0x8000) == !!(value & 0x4000)) ? (static_signbits<(short)((unsigned)value << 1)>::result + 1) : 0 };
};

clang 是正确的,因为左移负数是 undefined behavior