tags:

views:

139

answers:

3
+3  Q: 

C++ closure hack

is there any problem with such closure implementation (stolen from python 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

+2  A: 

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();
}
Potatoswatter
right, I just posted short sample to give idea
aaa
one of this months I guess I need to start using 0x
aaa
A: 

That's the basis of many of the functors that are used with STL algorithms. For instance, for_each, accumulate, and the veritable find_if all take or accept functors in their arguments. In fact, ptr_fun and mem_fun_ref construct such creations just to wrap functions into functors.

wheaties
+1  A: 

The C++ equavelent 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.
}
Martin York