简体   繁体   English

C++ 14 中的用户高阶函数

[英]User higher order functions in C++ 14

I'd like to create a class that accepts a function which was created by another function in Arduino. The "closest" I got after searching and a lot of trial and error (without std::function as we're in Arduino and C++ 14):我想创建一个接受std::function的class 14):

in foo.hfoo.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 { ... }
    }
};

in foo.cppfoo.cpp

template<typename Functor>
Foo::Foo (Functor lambda) : _lambda(lambda) {}

in bar.cppbar.cpp

new Foo(Foo::create_lambda(2));

The code above produces a number of errors including:上面的代码会产生许多错误,包括:

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

Also, happy to go with C++ 17 if that helps.另外,如果有帮助,请联系 go 和 C++ 17。

The class has to be templated, rather than the member:必须模板化 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);
    }
};

In C++17, we can make it figure out the type of F automatically when making a Foo by adding a template deduction guide for Foo :在 C++17 中,我们可以通过添加Foo的模板推导指南,使其在创建Foo时自动判断F的类型:

// Put this after the class declaration
template <class F>
Foo(F) -> Foo<F>;

Then, we can use it pretty easily!然后,我们就可以很容易地使用它了!

// Template parameter is implicit
Foo myFoo = [](int x) { return x * x; };
// myFoo now has type Foo<(anonymous lambda)>

If you absolutely need runtime polymorphism, you can have an interface that each Foo<F> extends:如果你绝对需要运行时多态性,你可以有一个每个Foo<F>扩展的接口:

class Invokable {
    virtual int invoke(int) = 0;
    virtual ~Invokable() = default;  
};

template <class F>
class Foo : Invokable {
    // ...
};

This article about the way std::function is implemented provides more details than I can in a stack overflow post: https://shaharmike.com/cpp/naive-std-function/这篇关于std::function实现方式的文章提供了比我在堆栈溢出帖子中更详细的信息: https://shaharmike.com/cpp/naive-std-function/

Addendum: You can see a working example here.附录: 您可以在此处查看工作示例。

When compiled with optimization, the assembly is extremely compact.优化编译时,程序集非常紧凑。 One of the benefits of C++ is that there's no overhead in using lambdas or templates, and they're entirely transparent to the compiler. C++ 的好处之一是使用 lambda 或模板没有开销,而且它们对编译器是完全透明的。

(Virtual functions are NOT transparent, which is why I do my best to avoid them, but sometimes you really need runtime polymorphism) (虚函数不是透明的,这就是为什么我尽力避免它们,但有时你真的需要运行时多态性)

.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM