【问题标题】:template metaprogramming - g++ eats it, clang does not模板元编程 - g++ 吃掉它,clang 不吃
【发布时间】:2019-03-10 15:58:56
【问题描述】:

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

为此:

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

【问题讨论】:

    标签: c++ metaprogramming generic-programming


    【解决方案1】:

    这是因为 clang 不支持常量表达式中的negative &lt;&lt; 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 2013-06-15
      相关资源
      最近更新 更多