什么是用于的函数类型? [英] What is a function type used for?
问题描述
给定以下两个 typedef
s:
typedef void (*pftype)(int);
typedef void ftype(int);
我理解第一个定义 pftype
一个指向一个具有 int
参数并且不返回任何内容的函数的指针,第二个函数定义 ftype
需要一个 int
参数并不返回任何内容。
I understand that the first defines pftype
as a pointer to a function that takes one int
parameter and returns nothing, and the second defines ftype
as a function type that takes one int
parameter and returns nothing. I do not, however, understand what the second might be used for.
我可以创建一个与这些类型匹配的函数:
I can create a function that matches these types:
void thefunc(int arg)
{
cout << "called with " << arg << endl;
}
然后我可以使用以下函数创建指向这个函数的指针:
and then I can create pointers to this function using each:
int main(int argc, char* argv[])
{
pftype pointer_one = thefunc;
ftype *pointer_two = thefunc;
pointer_one(1);
pointer_two(2);
}
当使用函数类型时,我必须指定我创建指针。使用函数指针类型,我不。两者都可以作为参数类型互换使用:
When using the function type, I have to specify that I'm creating a pointer. Using the function pointer type, I do not. Either can be used interchangeably as a parameter type:
void run_a_thing_1(ftype pf)
{
pf(11);
}
void run_a_thing_2(pftype pf)
{
pf(12);
}
因此,什么是函数类型?
What use, therefore, is the function type? Doesn't the function pointer type cover the cases, and do it more conveniently?
推荐答案
除了你指出的用法之外, (指针的基本类型或对函数的引用),函数类型的最常见用法是在函数声明中:
As well as the use you point out (the underlying type of a pointer or reference to a function), the most common uses for function types are in function declarations:
void f(); // declares a function f, of type void()
code> typedef :
for which one might want to use a typedef
:
typedef void ft(some, complicated, signature);
ft f;
ft g;
// Although the typedef can't be used for definitions:
void f(some, complicated, signature) {...}
并作为模板参数:
std::function<void()> fn = f; // uses a function type to specify the signature
这篇关于什么是用于的函数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!