2

I want to my function get_source to return a std::source_location type by taking a another function as an argument.

For example, I have a function named helloMessage and sumOf with the following argument types and return type:

void helloMessage(const char* message);
int sumOf(int num1, int num2); 

And supposed I have a function that will get a source location from the function object and then return its value:

template <typename function_t>
std::source_location get_source(function_t func);

Input:

auto info_1 = get_source(helloMessage);
auto info_2 = get_source(sumOf); 

std::cout 
<< "info_1: " << info_1.function_name() << '\n'
<< "info_2: " << info_2.function_name() << '\n';

This is my expected output:

void helloMessage(const char*)
int sumOf(int, int)

How can I achieve this?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Desmond Gold
  • 1,517
  • 1
  • 7
  • 19
  • 2
    There’s no way in the language to get a function name from a function pointer. You could pass the function as a template argument and get closer via `std::type_info`, or else use a platform-specific backtrace library. – Davis Herring May 02 '21 at 07:11
  • 1
    Review Jason Turner's excellent video on the topic of [std::source_location](https://www.youtube.com/watch?v=TAS85xmNDEc) for appropriate examples. – Casey May 02 '21 at 07:18

1 Answers1

1

source_location::current is always the ultimate source of any source_location object. source_location is serious about being the location in the source of the code that created that object.

So there is no way to turn a function into the location in the source that it came from. Not unless that function object has stored the source location of that function somewhere, which would be pretty difficult.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • @DavisHerring: I could swear I saw something about that in the standard, but I looked both there and in the proposals, and couldn't find anything. Oh well. – Nicol Bolas Aug 11 '21 at 19:02