Delegate in C++11

后端 未结 5 886
悲&欢浪女
悲&欢浪女 2021-02-14 00:09

Does C++11 provide delegates?

If not, what is the best (most efficient) way to do something similar in C++? Boost.Signals? FastDelegate? Something else?

5条回答
  •  一个人的身影
    2021-02-14 00:18

    The C mechanism has always been function pointer & baton (except for qsort() and bsearch() which didn't take a baton).

    So one would always pass the class object as the baton.

    E.G.:

    class tp {
        public:
            tp() { n = 0; }
            void m(int z) { printf("%d is %d\n", n++, z++); }
            int n;
    };
    
    void higher_func(int *opx, int cnt, void *handler(int itm, void *baton), void *baton)
    {
        for (int i = 0; i < cnt; i++)
            handler(opx[itm], baton);
    }
    
    /* You would need to provide this stub -- potentially templateable */
    void translate_baton(int itm, void *baton) { ((tp *)baton)->m(itm); }
    
    /* used like so: */
    int main()
    {
        int array[7];
    
        //...
        tp cx;
        higher_func(array, 7, translate_baton, &cx);
    }
    

提交回复
热议问题