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?

2
  • 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. Commented May 2, 2021 at 7:11
  • 1
    Review Jason Turner's excellent video on the topic of std::source_location for appropriate examples. Commented May 2, 2021 at 7:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.