c++ - 函数类型用于什么?

标签 c++ function function-pointers

给定以下两个typedef:

typedef void (*pftype)(int);

typedef void ftype(int);

我知道第一个将 pftype 定义为指向一个函数的指针,该函数接受一个 int 参数并且不返回任何内容,第二个定义 ftype 作为一种函数类型,它接受一个 int 参数并且不返回任何内容。但是,我不明白第二个可能用于什么。

我可以创建一个匹配这些类型的函数:

void thefunc(int arg)
{
    cout << "called with " << arg << endl;
}

然后我可以使用 each 创建指向该函数的指针:

int main(int argc, char* argv[])
{
    pftype pointer_one = thefunc;
    ftype *pointer_two = thefunc;

    pointer_one(1);
    pointer_two(2);
}

当使用函数类型时,我必须指定我正在创建一个指针。使用函数指针类型,我没有。两者都可以作为参数类型互换使用:

void run_a_thing_1(ftype pf)
{
    pf(11);
}

void run_a_thing_2(pftype pf)
{
    pf(12);
}

因此,函数类型有什么用处?函数指针类型是不是覆盖了case,做起来更方便?

最佳答案

除了您指出的用途(指针的基础类型或对函数的引用)之外,函数类型最常见的用途是在函数声明中:

void f(); // declares a function f, of type void()

可能需要使用 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

关于c++ - 函数类型用于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590084/

相关文章:

c - 是否有 typedef 函数指针的替代语法?

c++ - C++ 函数声明中,右括号前的 & 符号有何作用?

c++ - 通过组合来实现引用计数可以吗?

c++ - 在成员函数的参数列表中查找名称

c - 有没有办法避免在回调函数中使用静态变量?

javascript - 是否可以将回调内的数据传递给其包装的函数?

c++ - 从 C++/CLI 调用 DLL 函数时的 PInvokeStackImbalance

javascript - 如何创建多个对象,每个对象加载相同的页面但在 javascript 中具有不同的数据?

c++ - pthread_create C++ 中的无效转换

c - 帮助编译器优化函数指针