C++关闭hack

Any*_*orn 8 c++ closures

这样的闭包实现有什么问题(从python hack中被盗)?

void function(int value) {
    struct closure {
        closure(int v = value) : value_(value) {}
        private: int value_;
    };
    closure c;
}
Run Code Online (Sandbox Code Playgroud)

经过进一步调查,它出现在成员函数中,局部变量不能用作默认值,但是对象变量可以.

Pot*_*ter 6

这似乎是一个关闭的良好基础.更多的是成语而不是黑客,因为你合法地将语言功能用于其预期目的.

当然,你的例子没有做任何事情.它只能在内部使用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();
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ork 6

闭包的C++等价物:

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.
}
Run Code Online (Sandbox Code Playgroud)

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

int main()
{
    std::string g("Hello");

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

    c("World");
}
Run Code Online (Sandbox Code Playgroud)

使用C++ 14中的新扩展lambda语法(gcc上的-std = c ++ 1y),它变得更加容易.

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

    c("World");
}
Run Code Online (Sandbox Code Playgroud)