gpt4 book ai didi

C++ 动态定义函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:13:31 28 4
gpt4 key购买 nike

我正在使用 Visual C++ 开发控制台计算器,我正在创建一种让用户定义自定义线性函数的方法。这是我感到困惑的地方:一旦我获得了用户想要的函数名称、斜率和 y 轴截距,我需要使用该数据创建一个可调用函数,我可以将其传递给 muParser。

在 muParser 中,您可以像这样定义自定义函数:

double func(double x)
{
return 5*x + 7; // return m*x + b;
}

MyParser.DefineFun("f", func);
MyParser.SetExpr("f(9.5) - pi");
double dResult = MyParser.Eval();

我如何根据用户输入的值“m”和“b”动态创建这样的函数并将其传递给“DefineFun()”方法?这是我到目前为止所拥有的:

void cb_SetFunc(void)
{
string FuncName, sM, sB;
double dM, dB;
bool GettingName = true;
bool GettingM = true;
bool GettingB = true;
regex NumPattern("[+-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?");

EchoLn(">>> First, enter the functions name. (Enter 'cancel' to abort)");
EchoLn(">>> Only letters, numbers, and underscores can be used.");

try
{
do // Get the function name
{
Echo(">>> Enter name: ");
FuncName = GetLn();
if (UserCanceled(FuncName)) return;

if (!ValidVarName(FuncName))
{
EchoLn(">>> Please only use letters, numbers, and underscores.");
continue;
}
GettingName = false;

} while (GettingName);

do // Get the function slope
{
Echo(">>> Enter slope (m): ");
sM = GetLn();
if (UserCanceled(sM)) return;

if (!regex_match(sM, NumPattern))
{
EchoLn(">>> Please enter any constant number.");
continue;
}
dM = atof(sM.c_str());
GettingM = false;

} while (GettingM);

do // Get the function y-intercept
{
Echo(">>> Enter y-intercept (b): ");
sB = GetLn();
if (UserCanceled(sB)) return;

if (!regex_match(sB, NumPattern))
{
EchoLn(">>> Please enter any constant number.");
continue;
}
dB = atof(sB.c_str());
GettingB = false;

} while (GettingB);

// ------------
// TODO: Create function from dM (slope) and
// dB (y-intercept) and pass to 'DefineFun()'
// ------------
}
catch (...)
{
ErrMsg("An unexpected error occured while trying to set the function.");
}
}

我在想没有办法为每个用户定义的函数定义一个单独的方法。我需要做一个vector<pair<double, double>> FuncArgs;吗?跟踪适当的斜率和 y 截距然后从函数中动态调用它们?当我将它传递给 DefineFun(FuncStrName, FuncMethod) 时,我将如何指定要使用的对? ?

最佳答案

您需要的(除了脚本语言解释器)称为 "trampoline" .没有创建这些的标准解决方案,特别是因为它涉及在运行时创建代码。

当然,如果你接受固定数量的蹦床,你可以在编译时创建它们。如果它们都是线性的,这可能会更容易:

const int N = 20; // Arbitrary
int m[N] = { 0 };
int b[N] = { 0 };
template<int I> double f(double x) { return m[I] * x + b; }

这定义了一组 20 个函数 f<0>...f<19>使用m[0]...m[19]分别。

编辑:

// Helper class template to instantiate all trampoline functions.
double (*fptr_array[N])(double) = { 0 };
template<int I> struct init_fptr<int I> {
static const double (*fptr)(double) = fptr_array[I] = &f<I>;
typedef init_fptr<I-1> recurse;
};
template<> struct init_fptr<-1> { };

关于C++ 动态定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12404307/

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