Home > Article > Backend Development > How to Use `std::source_location` with Variadic Template Functions?
Problem:
The C 20 feature std::source_location provides context information during function calls. However, its integration with variadic template functions poses challenges due to the fixed position of variadic arguments.
Failed Attempts:
Solution using a Deduction Guide:
To resolve this issue, a deduction guide can be used:
<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>
By specifying a deduction guide, the compiler can infer the correct types for the variadic template function.
Test:
<code class="cpp">int main() { debug(5, 'A', 3.14f, "foo"); }</code>
This code compiles successfully and prints the provided arguments along with their source location.
DEMO: [link provided in original question]
The above is the detailed content of How to Use `std::source_location` with Variadic Template Functions?. For more information, please follow other related articles on the PHP Chinese website!