现代C++执行函数返回指针的方法

Modern C++ way of doing function return pointer to a function

本文关键字:指针 方法 返回 函数 C++ 执行 现代      更新时间:2023-10-16

我是C++新手,我开始阅读一本关于这个主题的书。有一个练习说:"声明一个指针,指向一个函数,将 int 作为参数,并返回一个指针,该函数将 char 作为参数并返回 float"。我最终得到了这段代码:

#include <iostream>
using namespace std;
float func(char c) {
    return 3.14;
}
float((*fun2(int))(char)) {
    return &func;
}
int main() {
    float(*fp)(char) = fun2(3);
    cout << fp('c') << endl;
}

问题是:在今天的C++编程中,它是否仍然合适。如果是这样 - 是否需要对代码进行任何必要的更改(应用新的抽象等(?谢谢。

可以声明类型别名:

using my_fp = float ( * )(char); // can work before C++11 with typedef
my_fp fun2(int){
  return &func;
}
my_fp fp = fun2(0);

和/或全自动类型扣除:

auto fun2(int) { // available in C++14
  return &func;
}
// Use a suitable value in the call to fun2
auto fp{fun2(0)}; // available in C++11

由于问题状态是返回"函数指针",因此您有点坚持使用稍微旧的语法。但是,如果您不受此约束,只想返回一个函数(并且 C 互操作性不是问题(,则可以使用 std::function ,这是一种更现代、更通用的函数类型。

#include <functional>
// ...
std::function<float(char)> fun2(int) {
  return &func;
}

std::function的优点(除了看起来比笨拙的float(*)(char)语法更漂亮(是它可以存储函数指针、匿名函数和可调用对象,而传统的函数指针只能存储指向全局函数的指针。因此,例如,允许以下内容。

struct Foo {
  float operator()(char) {
    // ...
  }
};
std::function<float(char)> fun3(int) {
  return Foo();
}
std::function<float(char)> fun4(int) {
  return [](char) { return 1.0; };
}

fun3fun4都不会使用简单的函数指针进行编译。

我的文字版本:

#include <iostream>
using my_pf = float(*)(char);
using my_ppf = my_pf(*)(int);
float func(char)
{
    return 3.14f;
}
my_pf fun2(int)
{
    return &func;
}

int main()
{
    my_ppf ppf; // Your declaration: 
                // Pointer to a function taking an int as argument
                // and returning a pointer to a function
                // that takes a char as argument and returns float.
    ppf = &fun2; 
    my_pf pf = ppf(3);
    std::cout << pf('c') << 'n';
}

作为替代方法,有尾随返回类型(自 C++11 起(:

auto fun2(int) -> float(*)(char)
{
    return &func;
}