void(int)& void(*)(int) [英] difference between void(int) & void (*)(int)
问题描述
我知道 void(*)(int)
是函数指针,但是 void(int)
?
I know void (*)(int)
is to function pointer but what is void(int)
?
它用于 std :: function
模板。
说我有一个函数 void fun(int){}
: decltype ; fun)
给予 void(*)(int)
但是 decltype(fun)
void(int)
Say I have a function void fun(int){}
: decltype(&fun)
gives void(*)(int)
but decltype(fun)
gives void(int)
推荐答案
如果 T
是一个类型,则 T *
表示类型指针 - T
。
If T
is a type, then T*
denotes the type "pointer-to-T
".
类型 void(int)
是一个函数类型的函数取一个 int
并返回 void
。例如, f
如果 f
被声明为 void f );
The type void(int)
is a function type, it's the type of a function taking one int
and returning void
. For example, it is the type of f
if f
is declared as void f(int);
如果 T = void(int)
c> T * 拼写为 void(*)(int)
,因此后者是函数指针的类型。您还可以形成对函数的引用,即 T& = void(&)(int)
;这有时更有用(例如,你可以获取函数lvalue的地址)。
If T = void(int)
, then T*
is spelled void(*)(int)
, so the latter is the type of a function pointer. You can also form a reference to a function, which is T& = void(&)(int)
; this is occasionally more useful (e.g. you can take the address of a function lvalue).
另外注意:函数lvalues 衰减到它们的函数指针。您可以通过函数lvalue或通过函数指针调用函数。当用作间接运算符( *
)的操作数时,函数值衰减,因此可以一次又一次解除引用指针:
Aside note: Function lvalues decay to their function pointer very easily. You can call a function either via a function lvalue or via a function pointer. When used as an operand for the indirection operator (*
), the function value decays, so you can dereference the pointer again and again:
printf("Hello world\n"); // OK
(*printf)("Hello world\n"); // also OK
(****printf)("Hello world\n"); // four-star programmer
一些函数不衰减的时候,操作符的操作数或绑定到引用时的操作数:
Some of the only times that a function does not decay is when used as the operand of the address-of operator, or when bound to a reference:
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
这篇关于void(int)& void(*)(int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!