How to get a source location from the function as argument without using static member function `current`?

459 views Asked by At

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?

1

There are 1 answers

1
Nicol Bolas On BEST ANSWER

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.