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
可以在可变参数模板中无缝使用的评论中告诉我std::source_location
,但是我很难弄清楚该如何做。如何std::source_location
与可变参数模板函数一起使用?
通过添加推导指南,可以使第一种形式起作用:
template <typename... Ts>
struct debug
{
debug(Ts&&... ts, const std::source_location& loc = std::source_location::current());
};
template <typename... Ts>
debug(Ts&&...) -> debug<Ts...>;
测试:
int main()
{
debug(5, 'A', 3.14f, "foo");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句