What exactly does the following code declare;
using f1 = void(int);
I know that the following;
using f2 = void(*)(int);
using f3 = void(&)(int);
f2
is a pointer to a function and f3
would be the reference.
It's a function type. When you declare a function, such as:
void func(int);
its type is not a pointer nor a reference. The above function's type is void(int)
.
We can "prove" it by using type traits as follows:
void func(int) {}
int main() {
std::cout << std::is_same<decltype(func), void(int)>::value << '\n';
std::cout << std::is_same<decltype(func), void(*)(int)>::value << '\n';
std::cout << std::is_same<decltype(func), void(&)(int)>::value << '\n';
}
The above code will return true
only for the first row.
No, but a function lvalue can be implicitly converted to a function pointer as per:
§4.3/1 Function-to-pointer conversion [conv.func]
An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function.
The relationship between a function type A(Args...)
and its reference (namely A(&)(Args...)
) is basically the same as the relationship between any type T
and its reference (namely T&
).
It's often used as a template parameter.
For example std::function
takes a function type to be stored inside the std::function
object and you can declare such an object with:
std::function<void(int)> fn;