gpt4 book ai didi

c++ - 为什么 noexcept 说明符在完整的类上下文中不起作用,但默认参数和函数体却起作用

转载 作者:行者123 更新时间:2023-12-05 03:17:44 24 4
gpt4 key购买 nike

我正在使用列出的书籍学习 C++ here .特别是,我阅读了完整类上下文并了解到它包括函数体、默认参数、noexcept-specifier 等。现在,为了进一步明确我对该主题的理解,我编写了以下程序,其中 # 1#2 有效,但 #3 失败。我不知道为什么 #3 失败,因为我读到所有三个(函数体、默认参数和 noexcept 说明符)都包含在完整类上下文中。

struct A {
constexpr static bool func()
{
return true;
}
//--------------vvvvvv------->works as expected #1
void f(bool V1 = func())
{
bool V2 = func(); //works as expected #2
}
//-----------------vvvvvv---->DOESN'T WORK? #3
void g() noexcept(func())
{
;
}

};

A complete-class context of a class is a

  • function body
  • default argument
  • noexcept specifier

如您所见,第三点是“noexcept specifier”,所以我希望 #3 也能正常工作,但事实并非如此。

所以我的问题是为什么#3#1#2 不同? Demo

GCC 给出了 #3 的错误:

 error: 'static constexpr bool A::func()' called in a constant expression before its definition is complete
20 | void g() noexcept(func())

Clang 给出:

error: noexcept specifier argument is not a constant expression
void g() noexcept(func())
^~~~~~
<source>:20:23: note: undefined function 'func' cannot be used in a constant expression
<source>:10:26: note: declared here
constexpr static bool func()

MSVC 给出:

 error C2131: expression did not evaluate to a constant
<source>(20): note: failure was caused by call of undefined function or one not declared 'constexpr'
<source>(20): note: see usage of 'A::func'

最佳答案

该程序格式良好并且所有三个编译器在拒绝代码方面都是错误的,因为 noexcept-specifier 包含在 complete-问题中引用的类上下文。

以下是相应的错误报告:

GCC rejects use of static constexpr member function in noexcept complete-class context

Clang rejects use of static constexpr member function in noexcept complete-class context

MSVC rejects use of static constexpr member function in noexcept complete-class context

关于c++ - 为什么 noexcept 说明符在完整的类上下文中不起作用,但默认参数和函数体却起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73998553/

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