如何在函数内定义和返回函数?
例如,我们有一个类似的功能:
float foo(float val) {return val * val;}
Run Code Online (Sandbox Code Playgroud)
现在,需要的是像bar这样的函数:
typedef float (*func_t)(float)
// Rubish pseudo code
func_t bar(float coeff) {return coeff * foo();}
// Real intention, create a function that returns a variant of foo
// that is multiplied by coeff. h(x) = coeff * foo(x)
Run Code Online (Sandbox Code Playgroud)
到目前为止,我唯一想到的就是使用lambda或类.是否有一种直接的方式来做到这一点,而不是不必要的复杂?
std::function<float(float)> bar(float coeff)
{
auto f = [coeff](float x)
{
return coeff * foo(x);
};
return f;
}
Run Code Online (Sandbox Code Playgroud)
然后你会像这样使用它:
auto f = bar(coeff);
auto result = f(x);
Run Code Online (Sandbox Code Playgroud)