在 C++ 中,将局部函数或仿函数传递给全局函数是完全不可能的吗?似乎所有迹象都指向“不”。这似乎是解决像积分器这样的简单数学函数实现的最简单方法:
template<class integrand>
void integrate(integrand f) {
...
f();
...
}
int main() {
struct twofer {
int operator()(int i) const { return 2*i; }
};
integrate(twofer());
}
或类似的东西。这失败了,因为我无法将本地对象传递给模板。我知道新标准允许在这里使用 lambda 函数,但我现在不能使用新标准。我真的也希望在本地声明该函数,因为我认为它使事情变得可读,尤其是在它作为代理的真实代码中。我知道我可以将 twofer 放在一个充满可集成函数的类或结构中,但我再次认为这会破坏可读性。有没有其他选择?
最佳答案
您可以使用指向成员函数的指针,但函数应该是静态的。这对我有用:
#include <iostream>
using namespace std;
typedef int (*Integrand)(int i);
int integrate(Integrand f) {
return f(2)+f(3)+f(4);
}
int main() {
struct Twofer {
static int function(int i){return 2*i;}
} t;
cout << integrate (t.function) << "\n";
return 0;
}
关于c++ - 将局部函数作为参数传递给全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9132377/