模板元编程 - g++无法处理,clang可以

3

有没有办法让两个编译器都满意?

针对此问题:

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

1个回答

4
这是因为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是正确的,因为左移负数是未定义行为


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接