std::source_location::function_name

来自cppreference.com
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
 
constexpr const char* function_name() const noexcept;
(C++20 起)

返回与此对象所表示的位置关联的函数名,若存在。

参数

(无)

返回值

若此对象表示函数体内的位置,则返回对应于函数的名字的由实现定义的空终止字节字符串。

否则,返回空字符串。

示例

以下示例展示能如何用 std::source_location::function_name() 打印函数、构造函数、析构函数或重载的 operator() 的名字。

#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()

参阅

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