gpt4 book ai didi

c++ - 编译时的 std::experimental::source_location

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:25 25 4
gpt4 key购买 nike

std::experimental::source_location可能会在某个时候添加到 C++ 标准中。我想知道是否有可能将位置信息获取到编译时领域。本质上,我想要一个在从不同源位置调用时返回不同类型的函数。像这样的东西,虽然它没有编译因为 location对象不是 constexpr因为它是一个函数参数:

#include <experimental/source_location>

using namespace std::experimental;

constexpr auto line (const source_location& location = source_location::current())
{
return std::integral_constant<int, location.line()>{};
}

int main()
{
constexpr auto ll = line();
std::cout << ll.value << '\n';
}

这不编译,有一条关于

的消息
expansion of [...] is not a constant expression

关于 return std::integral_constant<int, location.line()>{}线。拥有source_location的方法有什么好处?是constexpr如果我不能使用它们?

最佳答案

正如 Justin 指出的,您的代码存在的问题是函数参数不是 constexpr,但在 constexpr! functions 中提到了以更有用的方式在 constexpr 函数中使用 source_location 的问题。提案说:

The "Library Fundamentals v. 2" TS contains a "magic" source_location class get to information similar to the FILE and LINE macros and the func variable (see N4529 for the current draft, and N4129 for some design notes). Unfortunately, because the "value" of a source_location is frozen at the point source_location::current() is invoked, composing code making use of this magic class is tricky: Typically, a function wanting to track its point of invocation has to add a defaulted parameter as follows:

void my_log_function(char const *msg,
source_location src_loc
= source_location::current()) {
// ...
}

This idiom ensure that the value of the source_location::current() invocation is sampled where my_log_function is called instead of where it is defined.

Immediate (i.e., constexpr!) functions, however, create a clean separation between the compilation process and the constexpr evaluation process (see also P0992). Thus, we can make source_location::current() an immediate function, and wrap it as needed in other immediate functions: The value produced will correspond to the source location of the "root" immediate function call. For example:

constexpr! src_line() {
return source_location::current().line();
}

void some_code() {
std::cout << src_line() << '\n'; // This line number is output.
}

所以这是目前一个悬而未决的问题。

关于c++ - 编译时的 std::experimental::source_location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52977593/

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