gpt4 book ai didi

c++ - consteval 包装器与 source_location

转载 作者:行者123 更新时间:2023-12-01 14:42:33 25 4
gpt4 key购买 nike

我在 C++20 模式下使用 GCC10 尝试了以下第一个变体:

consteval std::experimental::source_location there()
{
return std::experimental::source_location::current(); // Line 3
}

void f(const std::experimental::source_location& a = there()) // Line 6
{
std::cout << a.line() << std::endl;
}

int main(int pArgc, char* pArgv[])
{
std::cout << there().line() << std::endl; // Line 13
f(); // Line 14

return 0;
}

我期望得到以下输出:

13
14

但是我得到了:

3
3

然后我尝试了以下第二种变体:

consteval std::experimental::source_location there(const std::experimental::source_location& a = std::experimental::source_location::current())
{
return a; // Line 3
}

void f(const std::experimental::source_location& a = there()) // Line 6
{
std::cout << a.line() << std::endl;
}

我期望得到以下输出:

13
14

但是我得到了:

13
6

为什么代码会这样?有没有办法在不使用预处理器宏的情况下使其按预期运行?

更新:使用“constexpr”或“inline”而不是“consteval”的第二个变体适用于最新的 GCC。所以剩下的问题是:为什么“consteval”也不起作用?有人告诉我这不是一个标准问题,而是一个实现主题,所以我将把这个问题重新标记为 GCC。

最佳答案

source_location::current() 总是 为您提供调用它的确切位置。观察到的行为正是它应该如何工作的。

默认函数参数在调用站点上进行评估。这就是为什么第二个示例中的第一次调用返回“13”的原因。这也是包装在函数调用中时应该如何使用 source_location 的唯一方式(否则没有多大意义)。

关于c++ - consteval 包装器与 source_location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62628942/

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