[英]User higher order functions in C++ 14
我想创建一个接受std::function
的class 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
另外,如果有帮助,请联系 go 和 C++ 17。
必须模板化 class,而不是成员:
// Put this whole thing in the header file.
// It has to go there b/c templates have to be in the header.
template<class F>
class Foo {
F func;
public:
Foo() = default;
Foo(Foo const&) = default;
Foo(Foo&&) = default;
Foo(F f) : func(f) {}
// Example invoke member function
int invoke(int value) {
return func(value);
}
};
在 C++17 中,我们可以通过添加Foo
的模板推导指南,使其在创建Foo
时自动判断F
的类型:
// Put this after the class declaration
template <class F>
Foo(F) -> Foo<F>;
然后,我们就可以很容易地使用它了!
// Template parameter is implicit
Foo myFoo = [](int x) { return x * x; };
// myFoo now has type Foo<(anonymous lambda)>
如果你绝对需要运行时多态性,你可以有一个每个Foo<F>
扩展的接口:
class Invokable {
virtual int invoke(int) = 0;
virtual ~Invokable() = default;
};
template <class F>
class Foo : Invokable {
// ...
};
这篇关于std::function
实现方式的文章提供了比我在堆栈溢出帖子中更详细的信息: https://shaharmike.com/cpp/naive-std-function/
附录: 您可以在此处查看工作示例。
优化编译时,程序集非常紧凑。 C++ 的好处之一是使用 lambda 或模板没有开销,而且它们对编译器是完全透明的。
(虚函数不是透明的,这就是为什么我尽力避免它们,但有时你真的需要运行时多态性)
.LC0:
.string "The square of %i is %i\n"
main:
push rbx
xor ebx, ebx
.L2:
mov edx, ebx
mov esi, ebx
mov edi, OFFSET FLAT:.LC0
xor eax, eax
imul edx, ebx
add ebx, 1
call printf
cmp ebx, 11
jne .L2
xor eax, eax
pop rbx
ret
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.