我知道 void (*)(int)
是函数指针,但 void(int)
是什么?
用于std::function
模板。
假设我有一个函数 void fun(int){}
: decltype(&fun)
给出 void(*)(int)
但是decltype(fun)
给出 void(int)
最佳答案
如果T
是一个类型,那么T*
表示类型“pointer-to-T
”。
类型void(int)
是一个函数类型,它是一个函数的类型,一个int
返回void
。例如,如果 f
被声明为 void f(int);
f
的类型
如果T = void(int)
,那么T*
拼写为void(*)(int)
,所以后者是函数指针的类型。你也可以形成一个函数的引用,即T& = void(&)(int)
;这有时更有用(例如,您可以获取函数左值的地址)。
旁注:函数左值衰减到它们的函数指针很容易。您可以通过函数左值或函数指针调用函数。当用作间接运算符 (*
) 的操作数时,函数值会衰减,因此您可以一次又一次地取消引用指针:
printf("Hello world\n"); // OK
(*printf)("Hello world\n"); // also OK
(****printf)("Hello world\n"); // four-star programmer
函数不会衰减的唯一情况是用作地址运算符的操作数,或者绑定(bind)到引用时:
void f(int); // our example function
void(*p1)(int) = &f; // no decay of "f" here
void(*p2)(int) = f; // "f" decays
void(&r1)(int) = f; // no decay of "f" here
void g(void(&callback)(int), int n) {
callback(n);
}
g(f, 10); // no decay of "f" here
template <typename F, typename ...Args>
decltype(auto) h(F&& callback, Args&&... args) {
return std::forward<F>(callback)(std::forward<Args>(args)...);
}
h(f, 10); // no decay of "f" here
关于c++ - void(int) 和 void (*)(int) 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437557/