小编sts*_*tsp的帖子

具有不完整类型的 lambda 函数

以下代码可以正常编译:

\n
#include <cstddef>\n\nstruct A {\n    char a;\n    static constexpr int off(void) { return offsetof(A, a); }\n    static constexpr int (*off_p)(void) = off;\n};\n
Run Code Online (Sandbox Code Playgroud)\n

以下看似相似的代码\n仅使用 lambda 简称,但无法编译:

\n
#include <cstddef>\n\nstruct A {\n    char a;\n    static constexpr int (*off_p)(void) =\n         [](void) static constexpr ->int { return offsetof(A, a); };\n};\n
Run Code Online (Sandbox Code Playgroud)\n
$ g++ -std=c++23 bad.cpp \nIn file included from /usr/include/c++/13/cstddef:50,\n                 from bad.cpp:1:\nbad.cpp: In static member function \xe2\x80\x98A::<lambda()> static\xe2\x80\x99:\nbad.cpp:5:74: error: invalid use of incomplete type \xe2\x80\x98struct A\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n

所以基本上我有两个不同的问题,因为我不明白这里发生了什么。

\n
    \n
  1. 为什么在第一种情况下允许使用不完整类型?
  2. \n …

c++ c++23

6
推荐指数
1
解决办法
219
查看次数

C 链接重载在 C++ 中如何工作?

考虑这个例子:

\n
int foo(void);\nextern "C" int foo(void);\n\nint main()\n{\n    return foo();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

它出错了:

\n
$ g++ -c main.cpp\nmain.cpp:2:16: error: conflicting declaration of \xe2\x80\x98int foo()\xe2\x80\x99 with \xe2\x80\x98C\xe2\x80\x99 linkage\n    2 | extern "C" int foo(void);\n      |                ^~~\nmain.cpp:1:5: note: previous declaration with \xe2\x80\x98C++\xe2\x80\x99 linkage\n    1 | int foo(void);\n      |     ^~~\n
Run Code Online (Sandbox Code Playgroud)\n

这完全没问题。

\n

但是让我们交换前两行:

\n
extern "C" int foo(void);\nint foo(void);\n\nint main()\n{\n    return foo();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

现在它编译时没有任何错误,\n但是选择了 C 链接,即使\n最后找到了 C++ 链接。

\n

问题:

\n
    \n
  1. 为什么情况 2 可以编译,而情况 1 却失败?我希望他们也会有同样的行为方式。
  2. \n
  3. 对于可以编译的情况 2,为什么选择 C ​​链接以及是否可以更改它?
  4. \n …

c c++ overload-resolution

3
推荐指数
1
解决办法
295
查看次数

标签 统计

c++ ×2

c ×1

c++23 ×1

overload-resolution ×1