Namespaces
Variants

std::source_location:: function_name

From cppreference.net
Utilities library
constexpr const char * function_name ( ) const noexcept ;
(自 C++20 起)

返回与此对象所表示位置相关联的函数名称(如果存在)。

目录

参数

(无)

返回值

如果此对象表示函数体中的某个位置,则返回一个实现定义的以空字符结尾的字节字符串,该字符串对应于函数的名称。

否则,将返回空字符串。

示例

std::source_location::function_name 可用于获取函数(包括特殊函数)名称及其签名。

#include <cstdio>
#include <utility>
#include <source_location>
inline void print_function_name(
    const std::source_location& location = std::source_location::current())
{
    std::puts(location.function_name()); // 输出调用者名称
}
void foo(double &&) { print_function_name(); }
namespace bar { void baz() { print_function_name(); } }
template <typename T> auto pub(T) { print_function_name(); return 42; }
struct S {
    S() { print_function_name(); }
    S(int) { print_function_name(); }
    ~S() { print_function_name(); }
    S& operator=(S const&) { print_function_name(); return *this; }
    S& operator=(S&&) { print_function_name(); return *this; }
};
int main(int, char const* const[])
{
    print_function_name();
    foo(3.14);
    bar::baz();
    pub(0xFULL);
    S p;
    S q{42};
    p = q;
    p = std::move(q);
    [] { print_function_name(); }();
}

可能的输出:

int main(int, const char* const*)
void foo(double&&)
void bar::baz()
auto pub(T) [with T = long long unsigned int]
S::S()
S::S(int)
S& S::operator=(const S&)
S& S::operator=(S&&)
main(int, const char* const*)::<lambda()>
S::~S()
S::~S()

参见

返回此对象表示的行号
(公开成员函数)
返回此对象表示的列号
(公开成员函数)
返回此对象表示的文件名
(公开成员函数)