【问题标题】:Different behavior of the C++ gcc HEAD 10.0.0 20190 when requires clause is specified with a requires expression and without itC++ gcc HEAD 10.0.0 20190 在使用 requires 表达式和不使用它的情况下指定 requires 子句时的不同行为
【发布时间】:2019-11-28 15:59:53
【问题描述】:

考虑这两个演示程序 (sizeof( unsigned long ) == sizeof( unsigned long long ))。

第一个是

#include <iostream>

unsigned long f( unsigned long n )
    requires ( not( ( sizeof( unsigned long ) == sizeof( unsigned long long ) ) ) )
{
    return n;
}

int main()
{
    std::cout << f( 0 ) << '\n';
}

编译器报错

错误:无法调用函数'long unsigned int f(long unsigned int) 需要 !(sizeof (long unsigned int) == sizeof (long long unsigned int))'

但是当像这样在 requires 子句中使用 requires 表达式时

#include <iostream>

unsigned long f( unsigned long n )
    requires requires { not ( sizeof( unsigned long ) == sizeof( unsigned long long ) ); }
{
    return n;
}

int main()
{
    std::cout << f( 0 ) << '\n';
}

程序编译并运行。

这是编译器的错误还是我遗漏了什么?

【问题讨论】:

    标签: c++ gcc c++20


    【解决方案1】:

    这是正常的。以下:

    requires ( not( ( sizeof( unsigned long ) == sizeof( unsigned long long ) ) ) )
    

    表示如果条件为真,函数参与重载决议。在您的情况下,条件为假,因为在您的实现中,unsigned longunsigned long long 具有相同的大小。因此,该函数从重载决议中移除。

    另一方面,在以下方面:

    requires requires { not ( sizeof( unsigned long ) == sizeof( unsigned long long ) ); }
    

    内部requires 表达式是条件,它始终为真,因为它实际上只是测试其操作数是否格式正确,当然是正确的,无论它是真还是假。由于条件始终为真,因此该函数参与重载决议。

    延伸阅读:https://stackoverflow.com/a/54203135/481267

    【讨论】:

    • 谢谢。我没有专心。:)
    猜你喜欢
    • 2020-01-03
    • 2017-03-28
    • 2021-08-11
    • 2020-07-09
    • 2021-03-20
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多