C++ 中可以通过宏来获取函数的名称和变量的名称,__func__ 就是函数的名称。获取变量名称可以使用以下自定义宏

#define NAME(variable) (#variable)

例子:

#include <iostream>
#define NAME(variable) (#variable)

auto mysum(int a, int b)
{
std::cout << "function name: " << __func__ << std::endl;
std::cout << NAME(a) << " + " << NAME(b) << " = " << (a + b) << std::endl;
return a + b;
}

int main()
{
auto s = mysum(5, 10);
std::cout << typeid(s).name() << std::endl;
return 0;
}

输出如下:

function name: mysum
a + b = 15
int

在 C++ 20 中还引入了 source_location,通过该结构体可以直接获取文件名,当前代码所在行,列和函数的名称

例子:

#include <iostream>
#include <string_view>
#include <source_location>

void log(const std::string_view message,
const std::source_location location =
std::source_location::current())
{
std::cout << "file: "
<< location.file_name() << "("
<< location.line() << ":"
<< location.column() << ") `"
<< location.function_name() << "`: "
<< message << '\n';
}

template <typename T> void fun(T x)
{
log(x);
}

int main(int, char* [])
{
log("Hello world!");
fun("Hello C++20!");
}

输出如下:

file: D:\VS_Projects\HelloWorld\HelloWorld\main.cpp(24:5) `main`: Hello world!
file: D:\VS_Projects\HelloWorld\HelloWorld\main.cpp(19:5) `fun`: Hello C++20!