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.
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