gpt4 book ai didi

c++ - 获取 std::function 的名称

转载 作者:IT老高 更新时间:2023-10-28 21:44:59 27 4
gpt4 key购买 nike

在下面的玩具示例中,我想获取一个函数的名称。函数本身作为 std::function 参数给出。是否可以在 C++ 中获取 std::function 对象的名称?

void printName(std::function<void()> func){
//Need a function name()
std::cout << func.name();
}

void magic(){};

//somewhere in the code
printName(magic());

output: magic

否则我将不得不将函数的名称作为第二个参数。

最佳答案

不,没有。函数名(如变量名)被编译出来,因此它们在运行时不可见。

最好的办法是按照您自己的建议传递函数的名称(使用 std::stringconst char*)。 (或者,您可以基于 C++11 中引入的 __func__ 解决方案。)

关于c++ - 获取 std::function 的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37545327/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com