3 ms·
Does anyone know what std::source_location::function_name() returns inside a lambda? Is it the outer function name, or something like this: "foo()::<lambda()#1
by Tempest1981 3y ago
Does anyone know what std::source_location::function_name() returns inside a lambda? Is it the outer function name, or something like this:
"foo()::<lambda()#1>"
I remember writing some constexpr expressions to strip the lambda portion (which had a guid). Is there now an easier way?
- eklitzke 3y agoIf you make the lambda take the source location as a default parameter initialized to `std::source_location::current()` (which is the typical usage) then the default argument is created in the scope of the caller, so it would expand to the name of the function (and line number, etc.) calling the lambda rather than the lambda itself. If you want to literally capture the name of the lambda and the line number in the lambda you'd create the source_location within the lambda instead.
- dkersten 3y agoI just tested it: 1 #include <source_location> 2 #include <iostream> 3 int main() { 4 auto c = [](std::source_location loc1 = std::source_location::current()){ 5 std::source_location loc2 = std::source_location::current(); 6 std::cout << loc1.function_name() << ":" << loc1.line() << "\n"; 7 std::cout << loc2.function_name() << ":" << loc2.line() << "\n"; 8 }; 9 c(); 10 return 0; 11 } As eklitzke said, this results in (using gcc): int main():9 main()::<lambda(std::source_location)>:5
- Tempest1981 3y agoThanks! Is there a way to extract the undecorated (?) function name? ("main" in this case, without the return type or args) Maybe a helper class or formatter?
- dkersten 3y agoThe actual name format is implementation defined. Here's the output from clang 17: int main():9 auto main()::(anonymous class)::operator()(std::source_location) const:5 so your formatter/helper would need to be compiler-aware, although to extract “main” in both cases I suppose you can just grab everything between the first whitespace and (, although I assume both types would contain specifiers like const where included in the return type. I don’t know what MSVC outputs.
- Tempest1981 3y agoThanks again, I'll have to give it a try once we get on C++20