代码之家  ›  专栏  ›  技术社区  ›  Anycorn

C++闭合破解

  •  8
  • Anycorn  · 技术社区  · 15 年前

    这种闭包实现(从python hack偷来的)有什么问题吗?

    void function(int value) {
        struct closure {
            closure(int v = value) : value_(value) {}
            private: int value_;
        };
        closure c;
    }
    

    2 回复  |  直到 11 年前
        1
  •  6
  •   Potatoswatter    15 年前

    当然,你的例子没什么用。它只能在 function .

    免费C++ 0x插头:

    #include <functional>
    
    void some_function( int x ) { }
    
    void function( int value ) {
        struct closure {
             std::function< void() > operator()( int value )
                 { return [=](){ some_function( value ); }; }
        };
    
        auto a = closure()( value );
        auto b = closure()( 5 );
    
        a();
        b();
        b();
    }
    
        2
  •  6
  •   Loki Astari    11 年前

    class Closure
    {
        public:
            Closure(std::string const& g)
               :greet(g)
            {}
           void operator()(std::string const& g2)
           {
                std::cout << greet << " " << g2;
           } 
        private:
            std::string   greet;
    };
    
    int main()
    {
        Closure   c("Hello");
    
        c("World");  // C acts like a function with state. Whooo.
    }
    

    在C++ 11中使用新的lambda语法,它变得更容易。

    int main()
    {
        std::string g("Hello");
    
        auto c = [g](std::string const& m)  {std::cout << g << " " << m;};
    
        c("World");
    }
    

    在C++ 14中新扩展的lambda语法(gt= C++ +1y在GCC上)变得更容易。

    int main()
    {
        auto c = [g="Hello"](std::string const& m)  {std::cout << g << " " << m;};
    
        c("World");
    }