zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    使用uibesizerpath + Cashaplayer画椭圆
    国庆节,回乡
    慎用单例
    终于碰到iOS对象集合深拷贝的坑
    Oracle 按表名导出数据
    代理模式(Proxy Pattern)
    享元模式(Flyweight Pattern)
    外观模式(Facade Pattern)
    组合模式
    装饰者模式
  • 原文地址:https://www.cnblogs.com/time-is-life/p/9578346.html
Copyright © 2011-2022 走看看