gpt4 book ai didi

c++ - 如何使用函数指针或虚函数来允许另一个程序员定义函数的实现?

转载 作者:行者123 更新时间:2023-11-27 23:19:20 25 4
gpt4 key购买 nike

我正在编写一个执行一组基本操作的程序,但允许用户填写调用的特定函数(他们在编译前选择这些函数)。例如,我的程序可能会调用函数 filter(input,&output)但用户可以编写自己的过滤器。

我读到的可以解决这个问题的方法是函数指针和虚函数。看起来我可以按照

int (*pt2Filter)(float,&float) = NULL;
int IIRFilter(float input, float &output);
pt2Filter=&IIRFilter;

函数指针。但这并不能让我跟踪过滤器中的内部状态。

或者我可以上课 myClass用虚拟 filter函数,然后用户会生成一个 IIRmyClass 继承的类并覆盖 filter功能。

class myClass
{
virtual void Filter(float input, float &output);
...
};

class IIR : public myClass
{
float stateVariable;
virtual void Filter(float input, float &output);
}

void IIR::Filter(float input, float &output)
{ //IIR filter done here }

我想我的问题是如何在不知道 IIR 的情况下从我的程序调用过滤器函数类甚至存在?

或者如果我的做法完全错误,我该如何调用我的 Filter当我的目标是 1 时起作用:让用户定义他们想要的任何过滤器。 2:不允许用户更改我的源代码

更新 这可能没有我最初想象的那么困难。我创建了一个头文件,用户可以在其中说出他们希望 Filter 类使用以下行调用哪个函数

//User types this into "FunctionImplementations.h"
#include "IIR.h"
typedef IIR FilterImplementation;
//then I just type
#include "FunctionImplementations.h"
FilterImplementation.filter(); //Implements IIR classes filter function

最佳答案

有几种方法可以实现这种多态性。

主要问题是您需要编译时多态行为还是运行时多态行为。在第一种情况下,解决方案通常是定义一个函数(或类)模板来执行您的通用工作,并使用通用代码调用的可调用对象的类型对其进行参数化,以完成自定义部分的工作:

// This is how you would define your generic procedure
template<typename F> void do_something(F f, ...)
{
...
f(...);
...
}

// This is how you would use it...
void my_func(...) { ... };
do_something(&my_func, ...); // with a function pointer

do_something([] (...) { ... }, ...); // with a lambda

struct my_functor { operator void () (...) { ... } };
do_something(my_functor(), ...); // with a functor

如果定义自定义行为的对象类型仅在运行时确定,那么您有两种可能性:要么使用std::function<>用于封装回调,或者使用虚函数方法。我个人更喜欢前者,因为它不会强制你为了实现动态多态性而创建继承层次。

这就是您使用 std::function<> 的方式对象:

void my_func1(int, int) { ... }
void my_func2(int, int) { ... }

std::function<void(int, int)> fxn = &my_func1;
fxn(2, 3);
...
fxn = &my_func2;
fxn(3, 4);
...
fxn = [] (int x, int y) { ... };
fxn(4, 5)

这就是您如何利用它来定义您的通用过程:

void do_something(std::function<void(int, int)> f, ...)
{
...
f(3, 4);
...
}

此时,您可以调用do_something()任何可以分配给 std::function 的东西(即任何具有兼容签名的可调用对象)。

关于c++ - 如何使用函数指针或虚函数来允许另一个程序员定义函数的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14464297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com