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:
<code class="cpp">template <typename... Args> void debug(Args&&... args, const std::source_location& loc = std::source_location::current());</code>
fails because variadic parameters must reside at the end.
Second Attempt:
<code class="cpp">template <typename... Args> void debug(const std::source_location& loc = std::source_location::current(), Args&&... args);</code>
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:
<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 allows calls like:
<code class="cpp">int main() { debug(5, 'A', 3.14f, "foo"); }</code>
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.
The above is the detailed content of How to Use `std::source_location` with Variadic Template Functions in C 20?. For more information, please follow other related articles on the PHP Chinese website!