"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Use `std::source_location` with Variadic Template Functions in C++20?

How to Use `std::source_location` with Variadic Template Functions in C++20?

Posted on 2025-03-25
Browse:534

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

Resolving Source Location Woes in Variadic Template Functions

In C 20, capturing function calling context details is made possible with std::source_location. However, employing it with variadic template functions has proven challenging due to the positioning of the source_location parameter.

The Position Predicament

Invariably, variadic parameters inhabit the end of the parameter list. This hindered the use of std::source_location due to the following reasons:

  • First Attempt:

    template 
    void debug(Args&&... args, const std::source_location& loc = std::source_location::current());

    fails because variadic parameters must reside at the end.

  • Second Attempt:

    template 
    void debug(const std::source_location& loc = std::source_location::current(),
             Args&&... args);

    introduces ambiguity for callers as it interjects an unexpected parameter.

Solution: Embracing Deduction Guides

The initial form can be revitalized by introducing a deduction guide:

template 
struct debug
{    
    debug(Ts&&... ts, const std::source_location& loc = std::source_location::current());
};

template 
debug(Ts&&...) -> debug;

This allows calls like:

int main()
{
    debug(5, 'A', 3.14f, "foo");
}

Conclusion:

Through the utilization of deduction guides, C programmers can seamlessly incorporate std::source_location into variadic template functions to capture function call context information effortlessly.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3