std :: experimental :: source_location在编译时

Tob*_*ull 5 c++ templates compile-time c++-experimental std-source-location

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';
}
Run Code Online (Sandbox Code Playgroud)

这不会编译,有关于的消息

expansion of [...] is not a constant expression
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*our 7

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

"Library Fundamentals v.2"TS包含一个"魔术"source_location类获取类似于FILELINE宏以及func变量的信息(有关当前草案,请参阅N4529,对于某些设计说明,请参阅N4129).不幸的是,因为source_location的"值"在调用source_location :: current()时被冻结,所以组成使用这个魔术类的代码是很棘手的:通常,想要跟踪其调用点的函数必须添加一个默认参数如下:

void my_log_function(char const *msg,
                     source_location src_loc
                        = source_location::current()) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

这个习惯用法确保在调用my_log_function而不是在其定义的位置调用source_location :: current()调用的值.

然而,立即(即constexpr!)函数在编译过程和constexpr评估过程之间创建了一个清晰的分离(参见P0992).因此,我们可以使source_location :: current()成为一个立即函数,并根据需要将其包装在其他立即函数中:生成的值将对应于"根"立即函数调用的源位置.例如:

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

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

所以这是一个开放的问题.