【发布时间】:2019-12-24 02:45:00
【问题描述】:
C++20 特性std::source_location 用于捕获有关调用函数的上下文的信息。
当我尝试将它与可变参数模板函数一起使用时,我遇到了一个问题:我看不到放置 source_location 参数的地方。
以下不起作用,因为可变参数必须在末尾:
// doesn't work
template <typename... Args>
void debug(Args&&... args,
const std::source_location& loc = std::source_location::current());
以下也不起作用,因为调用者将被插入其中的参数搞砸:
// doesn't work either, because ...
template <typename... Args>
void debug(const std::source_location& loc = std::source_location::current(),
Args&&... args);
// the caller will get confused
debug(42); // error: cannot convert 42 to std::source_location
我在comment 中得知std::source_location 可以与可变参数模板无缝协作,但我很难弄清楚如何使用。如何将std::source_location 与可变参数模板函数一起使用?
【问题讨论】:
-
也许让
debug成为一个宏,在正确的参数位置(第一个)调用std::source_location::current()调用真正的“调试”函数? -
关于导致编辑的已删除 cmets:我们不能在 c++20 的模板中拥有自动函数参数吗?
-
@Someprogrammerdude 这将正常工作,但我认为如果没有更好的方法,这只是一个后备。使用宏以某种方式破坏了
std::source_location的目的 IMO :( -
@eerorika 是的,参数中允许
auto,但是我们可以提供42或"foo"作为源位置。 -
@NicolBolas 你是对的,作为一个可以在其值不变的情况下传递的常规对象绝对是 source_location 的一个优势。但我想说摆脱宏的能力也是一个优势,这就是我“打算”打败的目的。因此我同意这句话是不完整的,但它不是不正确的,是吗?所以对我来说这是无稽之谈并没有多大意义。 (我不知道如何在这里产生错误的格式......)
标签: c++ variadic-templates c++20 default-arguments std-source-location