简体   繁体   中英

C++ Dynamically Define Function

I am on visual c++ working on a console calculator, I am creating a way to let the user define a custom linear function. Here is where I am stumped: Once I get the users desired name of the function, the slope, and the y-intercept, I need to use that data to create a callable function that I can pass to muParser.

In muParser, you define custom functions like this:

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();

How could I dynamically create a function like this based on the users input for the values 'm' and 'b' and pass that to the 'DefineFun()' method? This is what I have so far:

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.");
    }
}

I was thinking that there isn't a way to define an individual method for each user-defined-function. Would I need to make a vector<pair<double, double>> FuncArgs; to keep track of the appropriate slopes and y-intercepts then call them dynamically from the function? How would I specify which pair to use when I pass it to DefineFun(FuncStrName, FuncMethod) ?

What you need (in addition to a script language interpreter) is called a "trampoline" . There is no standard solution to create those, in particular since it involves creating code at runtime.

Of course, if you accept a fixed number of trampolines, you can create them at compile time. And if they're all linear, this might be even easier:

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; }

This defines a set of 20 functions f<0>...f<19> which use m[0]...m[19] respectively.

Edit:

// 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> { };

GiNaC是C ++库,可以解析和评估数学表达式。

Try to embed to your application some script language. Years ago I was using Tcl for similar purpose - but I do not know what is the current time best choice.

Either you can start from Tcl or search yourself for something better:

See: Adding Tcl/Tk to a C application

I would keep it simple:

#include <functional>

std::function<double(double)> f;   // this is your dynamic function

int slope, yintercept;             // populate from user input

f = [=](double x) -> double { return slope * x + yintercept; };

Now you can pass the object f to your parser, which can then call f(x) at its own leisure. The function object packages the captured values of slope and yintercept .

Generating a fixed array of functions bindable to boost function.

Someone else already said about a similar method, but since I'd taken the time to write the code, here it is anyway.

#include <boost/function.hpp>

enum {
    MAX_FUNC_SLOTS = 255
};

struct FuncSlot
{
    double (*f_)(double);
    boost::function<double(double)> closure_;
};

FuncSlot s_func_slots_[MAX_FUNC_SLOTS];

template <int Slot>
struct FuncSlotFunc
{
    static void init() {
        FuncSlotFunc<Slot-1>::init();
        s_func_slots_[Slot - 1].f_ = &FuncSlotFunc<Slot>::call;
    }
    static double call(double v) {
        return s_func_slots_[Slot - 1].closure_(v);
    }
};
template <> struct FuncSlotFunc<0> {
    static void init() {}
};

struct LinearTransform
{
    double m_;
    double c_;
    LinearTransform(double m, double c)
        : m_(m)
        , c_(c)
    {}
    double operator()(double v) const {
        return (v * m_) + c_;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    FuncSlotFunc<MAX_FUNC_SLOTS>::init();

    s_func_slots_[0].closure_ = LinearTransform(1, 0);
    s_func_slots_[1].closure_ = LinearTransform(5, 1);

    std::cout << s_func_slots_[0].f_(1.0) << std::endl; // should print 1
    std::cout << s_func_slots_[1].f_(1.0) << std::endl; // should print 6

    system("pause");
    return 0;
}

So, you can get the function pointer with: s_func_slots_[xxx].f_ And set your action with s_func_slots_[xxx].closure_

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM