std :: experimental :: source_location在编译时

时间:2018-10-24 20:39:31

标签: c++ templates compile-time c++-experimental

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有什么好处?

1 个答案:

答案 0 :(得分:5)

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

  

“图书馆基础知识v。2” TS包含“魔术” source_location   类获得类似于 FILE LINE 宏的信息   和 func 变量(有关当前草案,请参见N4529,以及N4129   一些设计注意事项)。不幸的是,因为   source_location冻结在source_location :: current()为   使用这个魔术类来调用,编写代码很棘手:   通常,要跟踪其调用点的函数必须   添加默认参数,如下所示:

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

此惯用法可确保source_location :: current()的值   在调用my_log_function的地方而不是在哪里采样调用   它已定义。

     

立即函数(即constexpr!)创建干净的函数   编译过程和constexpr之间的分离   评估过程(另请参阅P0992)。因此,我们可以使   source_location :: current()一个立即函数,并将其包装为   其他即时功能所需的:产生的价值将   对应于“ root”立即函数的源位置   呼叫。例如:

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

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

所以这是目前尚待解决的问题。