• C++ delegate的几种方法


    https://stackoverflow.com/questions/9568150/what-is-a-c-delegate

    You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.


    Option 1 : functors:

    A function object may be created by implementing operator()

    struct Functor
    {
         // Normal class/struct members
    
         int operator()(double d) // Arbitrary return types and parameter list
         {
              return (int) d + 1;
         }
    };
    
    // Use:
    Functor f;
    int i = f(3.14);
    

    Option 2: lambda expressions (C++11 only)

    // Syntax is roughly: [capture](parameter list) -> return type {block}
    // Some shortcuts exist
    auto func = [](int i) -> double { return 2*i/1.15; };
    double d = func(1);
    

    Option 3: function pointers

    int f(double d) { ... }
    typedef int (*MyFuncT) (double d);
    MyFuncT fp = &f;
    int a = fp(3.14);
    

    Option 4: pointer to member functions (fastest solution)

    See Fast C++ Delegate (on The Code Project).

    struct DelegateList
    {
         int f1(double d) { }
         int f2(double d) { }
    };
    
    typedef int (DelegateList::* DelegateType)(double d);
    
    DelegateType d = &DelegateList::f1;
    DelegateList list;
    int a = (list.*d)(3.14);
    

    Option 5: std::function

    (or boost::function if your standard library doesn't support it). It is slower, but it is the most flexible.

    #include <functional>
    std::function<int(double)> f = [can be set to about anything in this answer]
    // Usually more useful as a parameter to another functions
    

    Option 6: binding (using std::bind)

    Allows setting some parameters in advance, convenient to call a member function for instance.

    struct MyClass
    {
        int DoStuff(double d); // actually a DoStuff(MyClass* this, double d)
    };
    
    std::function<int(double d)> f = std::bind(&MyClass::DoStuff, this, std::placeholders::_1);
    // auto f = std::bind(...); in C++11
    

    Option 7: templates

    Accept anything as long as it matches the argument list.

    template <class FunctionT>
    int DoSomething(FunctionT func)
    {
        return func(3.14);
    }
  • 相关阅读:
    php xdebug的配置、调试、跟踪、调优、分析
    alpine使用的避坑指南
    nginx fastcgi模块ngx_http_fastcgi_module详细解析、使用手册、完整翻译
    深入理解 Kubernetes 资源限制:CPU
    使用xdebug对php做性能分析调优
    alpine安装sshd/ssh server
    冒泡排序的终极改进优化
    基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建
    NPM使用
    NodeJS学习历程
  • 原文地址:https://www.cnblogs.com/time-is-life/p/9578346.html
Copyright © 2020-2023  润新知