void(*)(void)
is a function pointer while I suppose void(void)
is also a way to represent function type. It is used as template parameter in std::function
<functional>
What is void(void)
and how it is different from void(*)(void)
?
CodePudding user response:
Let's start by saying, that sometimes the void(void)
will be automatically treated as a pointer to function (i.e. in a parameter list). Then we still can be explicit and use the void(*)(void)
, but the void(void)
will be an equivalent.
// Here, we explicitly state that the f is a pointer to function
void foo(void (*f)(void), int i);
// Equivalent, f is automatically treated as a pointer to the function
void foo(void f(void), int i);
Which is not the case for the std::function
instantiation. The types of the two are different, yet may have similar behavior (i.e. we can use the function call operator on a pointer to function).
void bar();
// Prints 1
std::cout << std::is_same<void(void), decltype(bar)>::value << '\n';
// Prints 1 as well
// Note the pointer type specifier
std::cout << std::is_same<void(*)(void), decltype(bar)*>::value << '\n';
// Prints 0
// Note the absence of the pointer type specifier
std::cout << std::is_same<void(*)(void), decltype(bar)>::value << '\n';
The use of the std::function
instead of the function pointers has the same moto as using the smart pointers instead of the raw pointers.
N.B. unlike in the case of a parameter, the compiler won't treat the function type in a return as a pointer to function type. Thus, we must explicitly specify the pointer type in case of the return.
// Here, baz is a function that doesn't take any agruments
// And returns a pointer to a function that takes an int argument and "returns" void
void (*baz())(int);
CodePudding user response:
for void fun(){}
, std::is_same_v<void(void)>, decltype(fun)>
is true; and std::is_same_v<void(*)(void)>, decltype(&fun)>
is true. In fact, those are their real types. However, the standard approve you convert an object that has type void(void)
to void(*)(void)
implicitly (so you can even write (******funptr)()
), that's why we always confuse them.
CodePudding user response:
What is
void(void)
and how it is different fromvoid(*)(void)
?
They are distinct types. Although the former(void(void)
) can be implicitly converted to the latter(void(*)(void)
) in many contexts.
The type void(void)
is called a function type. The following are also function types:
int (int, int) //this is a function type
void(int) //this is a function type as well
On the other hand, void (*)(void)
is a pointer to a function type. That is, it is a pointer that points to a function with 0
parameters and return type of void
.