简体   繁体   中英

C++ - Setting a function equal to a parameter

I'm pretty new to c++ but I'm trying to port over a flash game I've started. I'm stuck trying to pass a function in as a parameter, and then set a property equal to that function.

class Param
{
    private:
    float function();
    float value;

    public:
    Param(float (func)());
    Param(float (func)(), float value);
    ~Param();

    void update();
};

I've tried something like:

Param::Param(float (func)()) {
    this.function = func;
}

But it doesn't seem to like that. I'm not sure if it needs to be a pointer either, I'd like to just specify it when the Param is instantiated rather than pass a reference that might get deleted to it.

EDIT: If someone could also answer, is there a way to make these passed in functions optional? As in a function for it to default to if none is specified?

Normally, you´ll need a pointer

class Param
{
    private:
    float (*function)();
    float value;

    public:
    Param(float (*func)());
    Param(float (*func)(), float value);
    ~Param();

    void update();
};

The & for the parameter in an actual call is not needed,
you can just pass the pure name of a function
(with or without &, but without any parenthesis!)

But: The passed function can´t be part of some class instance.
Only "raw" functions (maybe in a namepace) or static class methods.
Use a std::function to enable class instance methods and lambdas etc. too:

class Param
{
    private:
    std::function<float()> function;
    float value;
    public:
    Param(std::function<float()> func);
    Param(std::function<float()> func, float value);
    ~Param();

    void update();
};

A normal function like above can be passed anyways.
(Take a look at std::bind & Co to get an idea how to pass class methods)

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