在C++20中,立即函数的默认参数在哪个上下文中被替换(在源位置示例中)?

在 C++20 中添加了一个新功能来获取源位置信息:https : //en.cppreference.com/w/cpp/utility/source_location

这是该页面的一个稍微修改的示例,其中使用附加立即函数loc来获取源位置:

#include <iostream>
#include <string_view>
#include <source_location>
 
consteval auto loc(std::source_location x = std::source_location::current() ) { return x; }

void log(const std::string_view message,
         const std::source_location location = loc()) {
    std::cout << "file: "
              << location.file_name() << "("
              << location.line() << ":"
              << location.column() << ") `"
              << location.function_name() << "`: "
              << message << 'n';
}
 
template <typename T> void fun(T x) { log(x); }
 
int main(int, char*[]) {
    log("Hello world!");
    fun("Hello C++20!");
}

在最新的 MSVC 2019 中,它按照来自 cppreference.com 的原始示例进行打印:

file: main.cpp(25:5) `main`: Hello world!
file: main.cpp(20:5) `fun`: Hello C++20!

但是在 GCC 中,同一行在输出中显示了两次:

file: /app/example.cpp(8:51) ``: Hello world!
file: /app/example.cpp(8:51) ``: Hello C++20!

演示:https : //gcc.godbolt.org/z/nqE4cr9d4

哪个编译器就在这里?

如果定义loc函数不是直接函数:

auto loc(std::source_location x = std::source_location::current() ) { return x; }

然后 GCC 的输出改变并类似于原始示例:

file: /app/example.cpp(20:8) `int main(int, char**)`: Hello world!
file: /app/example.cpp(17:42) `void fun(T) [with T = const char*]`: Hello C++20!

虽然 MSVC 拒绝编译它并出现错误:

error C7595: 'std::source_location::current': call to immediate function is not a constant expression

演示:https : //gcc.godbolt.org/z/vorW4f9ax

还请建议,哪个编译器在非直接情况下也是正确的?

以上是在C++20中,立即函数的默认参数在哪个上下文中被替换(在源位置示例中)?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>