【发布时间】:2021-10-11 11:04:23
【问题描述】:
我想创建一个类来接受由 Arduino 中的另一个函数创建的函数。我在搜索和大量试验和错误后得到的“最接近”(没有std::function,因为我们在 Arduino 和 C++ 14 中):
在foo.h
class Foo {
private:
template<typename Functor>
Functor _lambda;
public:
template<typename Functor>
Foo(Functor lambda);
static auto create_lambda(int a) {
return [a](int b) mutable { ... }
}
};
在foo.cpp
template<typename Functor>
Foo::Foo (Functor lambda) : _lambda(lambda) {}
在bar.cpp
new Foo(Foo::create_lambda(2));
上面的代码产生了一些错误,包括:
error: data member '_lambda' cannot be a member template
error: 'Foo::Foo(Functor) [with Functor = Foo::create_lambda(int)::<lambda(bool)>]', declared using local type 'Foo::create_lambda(int)::<lambda(bool)>', is used but never defined
另外,如果有帮助的话,很高兴使用 C++ 17。
【问题讨论】:
-
你的代码有什么问题?
-
类成员不能是模板,只有类方法可以。抱歉,C++ 不能以这种方式工作。你的整个班级必须是一个模板。此外,还必须更改许多其他基本的东西才能使其工作(例如,将模板定义放在
.cpp文件中总是以泪水结束)。 C++17 也是如此,未来的所有其他 C++ 版本也可能如此。只需使用std::function,就更简单了。 -
@SamVarshavchik,听起来都不错,只是他们运行的 Arduino 环境可能没有
std::function,因此他们要求不使用。常见的基于 AVR 的 Arduino 环境提供了接近 C99 托管的 C 标准库的东西,但根本没有 C++ 标准库;没有std::swap或std::array,更不用说std::function。 -
所以你要求为arduino实现
std::function。 -
如果只将无星 lambda 传递给构造函数,则只需使用指向函数的指针。
标签: c++ arduino higher-order-functions