现代C++执行函数返回指针的方法
Modern C++ way of doing function return pointer to a function
我是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; };
}
fun3
和fun4
都不会使用简单的函数指针进行编译。
我的文字版本:
#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;
}
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 将成员函数指针作为参数传递给模板方法
- 通过函数指针定义类范围之外的方法
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- 如何访问由共享指针保存的类方法?
- 初始化指向类实例的智能指针并访问其方法
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在工厂方法中返回指向基于基础操作系统的派生类的有效指针
- 有没有将变量名称转换为双指针的简短方法?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 类指针方法崩溃程序
- 证明两指针方法有效(对和)
- Qt 删除指针方法
- 我如何将一些类的指针方法转换为指针函数