gpt4 book ai didi

c++ - 为什么将函数作为 &name 和 name 传递会给出不同的指针?

转载 作者:行者123 更新时间:2023-11-28 00:00:14 25 4
gpt4 key购买 nike

我有一个函数,我想调用另一个函数并打印它的名称并处理它的结果。效果不错

#include <iostream>
#include <string>
#include <map>

std::map<void *, std::string> ptr_map;
#define IS_API_CALL(fun) ptr_map[fun] = __FUNCTION__;

int api_call_bar(double x) {
IS_API_CALL(&api_call_bar);
return 0;
}

std::string getFuncNameByPtr(void * addr) {
for (auto it = ptr_map.begin(); it != ptr_map.end(); ++it) {
if (it->first == addr) return it->second;
}

return "???";
}

template <typename... Args>
void api_exec(int func(Args...), Args... args) {
func(args...);
auto name = getFuncNameByPtr(func); // <-- HERE. &func doesnt work
std::cout << name << " was called\n";
}

int main() {
api_exec(&api_call_bar, 2.0);
}

这一个打印 api_call_bar was called这很好。对我来说有趣的部分是标记为 <-- HERE 的部分.如果我将它传递为 &func它不再正常工作( map 中的指针找不到名称)。为什么会这样?我觉得应该是一模一样的。

最佳答案

函数参数声明的指针隐式转换给您带来了麻烦。由于您实际上不能将函数作为参数传递给函数,因此编译器(默默地——恕我直言,至少应该是一个警告)将函数类型转换为指针类型。所以当你声明时:

void api_exec(int func(Args...), Args... args)

真的就像你宣告的那样

void api_exec(int (*func)(Args...), Args... args)

这意味着当您在 api_exec 中使用 &func 时,您将获得一个指向参数的指针(因此是一个指向指针的指针),而不是争论。

同样的事情也发生在数组上,这也让没有意识到这一点的人感到困惑。

关于c++ - 为什么将函数作为 &name 和 name 传递会给出不同的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39690592/

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