c++ - void(int) 和 void (*)(int) 之间的区别

标签 c++

我知道 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/

相关文章:

c++ - 检查跳转缓冲区是否有效(非本地跳转)

c++ - 在 Rcpp 中实现应用功能

C++ 和谷歌测试

c++ - 类对象的模板

c++ - for循环中的RSA mpz_powm() : seg fault

c++ - Windows 8.1 项目的 Windows 10 Visual Studio 2013 构建错误

c++ - 为什么 null std::optional 被认为小于任何值,而不是更多

c++ - _mm_max_ss 在 clang 和 gcc 之间有不同的行为

矩阵窗口上的 Java 代码优化计算时间更长

c++ - 另一个 pthread 中的 V8 代码导致段错误