现代C ++做函数的方式返回指向函数的指针

时间:2018-01-15 17:53:40

标签: c++ pointers

我是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 ++编程中是否仍然适用。如果是这样 - 是否需要对代码进行任何更改(应用新的抽象等)?谢谢。

4 个答案:

答案 0 :(得分:4)

您可以声明类型别名:

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

答案 1 :(得分:2)

由于问题表明返回一个&#34;函数指针&#34;,你会遇到稍微陈旧的语法。但是,如果您不受此约束并且只想返回一个函数(并且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都不会使用简单的函数指针进行编译。

答案 2 :(得分:1)

我的文字版本:

#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';

}

答案 3 :(得分:1)

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

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