【发布时间】:2020-12-18 10:43:55
【问题描述】:
我试图构建代码来传递要在另一个函数中使用的函数。下面是我尝试过的代码,它在函数之外工作(所以如果我删除与类 Foo 相关的所有内容,它会工作),但我不知道如何让它在类本身内工作。如何在类中传递一个函数?我尝试了this->part1_math_class、Foo::part1_math_class 和part1_math_class,都没有成功。
// Example program
#include <iostream>
#include <string>
#include <stdint.h>
#include <functional>
int64_t loop(std::string partialMath, std::function<int64_t(std::string)> recurse)
{
while (partialMath.find("(") != std::string::npos)
{
auto posClose = partialMath.find(")");
auto posOpen = partialMath.rfind("(", posClose);
std::string sub = partialMath.substr(posOpen + 1, posClose - posOpen - 1);
int64_t resultInner = loop(sub, recurse);
partialMath.replace(posOpen, sub.size() + 2, std::to_string(resultInner));
}
return recurse(partialMath);
}
int64_t part1_math(std::string math)
{
return 0;
}
int64_t part2_math(std::string math)
{
return 1;
}
class Foo {
public:
Foo() { }
int64_t loop_class(std::string partialMath, std::function<int64_t(std::string)> recurse)
{
while (partialMath.find("(") != std::string::npos)
{
auto posClose = partialMath.find(")");
auto posOpen = partialMath.rfind("(", posClose);
std::string sub = partialMath.substr(posOpen + 1, posClose - posOpen - 1);
int64_t resultInner = loop_class(sub, recurse);
partialMath.replace(posOpen, sub.size() + 2, std::to_string(resultInner));
}
return recurse(partialMath);
}
int64_t part1_math_class(std::string math)
{
return 2;
}
int64_t part2_math_class(std::string math)
{
return 3;
}
int64_t runLoop()
{
return loop_class("(1 + 2)", Foo::part1_math_class);
}
};
int main()
{
std::cout << loop("(1 + 2)", part1_math) << std::endl; // this one works
Foo bar;
std::cout << bar.runLoop() << std::endl; // this one does not even compile
return 0;
}
【问题讨论】:
-
是否要将成员函数作为参数发送给另一个函数?
-
是的,但在同一个班级。我可以使用某种 if 逻辑来做同样的事情,但我只想传递函数(在同一个类中)来运行。
-
为什么不使用 lambda?
return loop_class("(1 + 2)", [this](std::string math) { return part1_math_class(math); });std::function可以与函数和仿函数一起使用。在这种情况下,lambda 提供匹配的函子(正确的签名)并绑定(捕获)this作为成员。
标签: c++