如何在可变参数模板函数中使用source_location? [英] How to use source_location in a variadic template function?

查看:147
本文介绍了如何在可变参数模板函数中使用source_location?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 20功能std::source_location用于捕获有关调用函数的上下文的信息. 当我尝试将其与可变参数模板函数一起使用时,遇到一个问题:我看不到放置source_location参数的地方.

The C++20 feature std::source_location is used to capture information about the context in which a function is called. When I try to use it with a variadic template function, I encountered a problem: I can't see a place to put the source_location parameter.

以下操作无效,因为可变参数必须在末尾:

The following doesn't work because variadic parameters have to be at the end:

// doesn't work
template <typename... Args>
void debug(Args&&... args,
           const std::source_location& loc = std::source_location::current());

以下方法也不起作用,因为调用者将被介于两者之间的参数所困扰:

The following doesn't work either because the caller will be screwed up by the parameter inserted in between:

// 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与可变参数模板函数一起使用?

I was informed in a comment that std::source_location works seamlessly with variadic templates, but I struggle to figure out how. How can I use std::source_location with variadic template functions?

推荐答案

可以通过添加演绎指南使第一种形式起作用:

The first form can be made to work, by adding a deduction guide:

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");
}

演示

这篇关于如何在可变参数模板函数中使用source_location?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆