gpt4 book ai didi

c++ - GCC 和 Clang 在与 __builtin_constant_p 相关的 static_assert 方面有所不同

转载 作者:行者123 更新时间:2023-12-04 11:40:25 24 4
gpt4 key购买 nike

我碰巧发现GCC和Clang在以下代码的编译上有所不同:

struct Foo
{
int mem = 42;
};

int main()
{
constexpr Foo foo;
static_assert(__builtin_constant_p(foo));
return 0;
}
我用 g++ -std=c++17 编译和 clang++ -std=c++17 .
特别是,
  • g++ g++-9 (Homebrew GCC 9.3.0_1) 9.3.0编译,而
  • clang++ Apple clang version 11.0.3 (clang-1103.0.32.62)编译失败,提示
  • error: static_assert failed due to requirement '__builtin_constant_p(foo)'
    static_assert(__builtin_constant_p(foo));
    ^ ~~~~~~~~~~~~~~~~~~~~~~~~~
    我没有发现任何关于 __builtin_constant_p 应该有任何区别的提示。 .
    对于 __builtin_constant_p GCC

    You can use the built-in function __builtin_constant_p to determine if a value is known to be constant at compile time ...


    Clang

    Clang supports a number of builtin library functions with the same syntax as GCC, including things like __builtin_nan, __builtin_constant_p, __builtin_choose_expr, __builtin_types_compatible_p, __builtin_assume_aligned, __sync_fetch_and_add, etc.


    问题:虽然我知道 __builtin_constant_p是一个编译器扩展,哪个应该是正确的?

    最佳答案

    两者都没有很好的记录,所以我怀疑你的问题是否有正确的答案。
    如果您需要解决方法:如果参数不是 int,似乎 clang 放弃了。
    所以这有效:

    struct Foo
    {
    int mem = 42;
    };

    int main()
    {
    constexpr Foo foo;
    static_assert(__builtin_constant_p(foo.mem));
    return 0;
    }

    关于c++ - GCC 和 Clang 在与 __builtin_constant_p 相关的 static_assert 方面有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62778436/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com