Define and return a function from a function?

前端 未结 2 1694
死守一世寂寞
死守一世寂寞 2021-01-24 07:38

How does one define and return a function inside a function?

For instance, we have a function like:

float foo(float val) {return val * val;}
2条回答
  •  天命终不由人
    2021-01-24 08:39

    Use std::function

    std::function bar(float coeff)
    {
        auto f = [coeff](float x)
        {
            return coeff * foo(x);
        };
    
        return f;
    }
    

    You would then use it like this:

    auto f = bar(coeff);
    auto result = f(x);
    

提交回复
热议问题