Home > Article > Backend Development > 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>
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>
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>
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>
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!