开发者

C++ closure hack

Is there any problem with such closure implementation (stolen from pyth开发者_高级运维on hack)?

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

Upon further investigation, it appears in member functions, local variables can not be used as default values, but object variables can.


That looks like a good basis to make a closure. More of an idiom than a hack, since you're legitimately using language features for their intended purpose.

Of course, your example doesn't do anything. And it can only be used within function.

Gratuitous C++0x plug:

#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();
}


The C++ equivalent of a closure:

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.
}

With the new lambda syntax in C++11 it becomes even easier.

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

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

    c("World");
}

With the new extended lambda syntax in C++14 (-std=c++1y on gcc) it becomes even easier.

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

    c("World");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜