std::source_location::function_name

From cppreference.com
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

Elementary string conversions
(C++17)
(C++17)
 
 
constexpr const char* function_name() const noexcept;
(since C++20)

Returns the name of the function associated with the position represented by this object, if any.

Parameters

(none)

Return value

If this object represents a position in a body of a function, returns an implementation-defined null-terminated byte string corresponding to the name of the function.

Otherwise, an empty string is returned.

Example

The following example shows how it is possible to use the std::source_location::function_name() to print a name of a function, constructor, destructor, or overloaded operator().

#include <iostream>
#include <string_view>
#include <source_location>
 
inline void function_name(
    const std::string_view signature = "()",
    const std::source_location& location = std::source_location::current())
{
    std::cout
        << location.function_name() // <- name of the caller!
        << signature
        << '\n';
}
 
void foo() { function_name(); }
 
struct S {
    S() { function_name(); }
    S(int) { function_name("(int)"); }
    S& operator=(S const&) { function_name("(const S&)"); return *this; }
    S& operator=(S&&) { function_name("(S&&)"); return *this; }
    ~S() { function_name(); }
};
 
auto main() -> int
{
    foo();
    S p;
    S q{42};
    p = q;
    p = std::move(q);
}

Output:

foo()
S()
S(int)
operator=(const S&)
operator=(S&&)
~S()
~S()

See also

return the line number represented by this object
(public member function)
return the column number represented by this object
(public member function)
return the file name represented by this object
(public member function)