Home > Backend Development > C++ > How to Use `std::source_location` in Variadic Template Functions?

How to Use `std::source_location` in Variadic Template Functions?

Mary-Kate Olsen
Release: 2024-10-30 19:08:45
Original
1066 people have browsed it

How to Use `std::source_location` in Variadic Template Functions?

Using std::source_location in Variadic Template Functions

When leveraging the C 20 feature std::source_location to capture context information in variadic template functions, a challenge arises in determining where to place the source_location parameter.

Failed Attempts

Incorrect attempts include:

  • Variadic Parameters at the End:

    <code class="cpp">template<typename... Args>
    void debug(Args&&... args, const std::source_location& loc = std::source_location::current());</code>
    Copy after login

This fails because variadic parameters must be at the end.

  • Parameter Insertion:

    <code class="cpp">template<typename... Args>
    void debug(const std::source_location& loc = std::source_location::current(),
    Args&&... args);</code>
    Copy after login

This confuses the caller, which would error when passing regular arguments (e.g., debug(42);).

Solution: Deduction Guide

The issue can be resolved by adding a deduction guide to the first form:

<code class="cpp">template<typename... Ts>
struct debug
{
    debug(Ts&&... ts, const std::source_location& loc = std::source_location::current());
};

template<typename... Ts>
debug(Ts&&...) -> debug<Ts...>;</code>
Copy after login

This deduction guide infers the template parameters based on the function arguments, allowing the source_location parameter to be placed at the end.

Test and Demonstration

<code class="cpp">int main()
{
    debug(5, 'A', 3.14f, "foo");
}</code>
Copy after login

Live Demo: https://godbolt.org/z/n9Wpo9Wrj

The above is the detailed content of How to Use `std::source_location` in Variadic Template Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template