Closures vs. Objects

A closure is a function that refers to a free lexical variable defined outside it, and that variable must persist as long as the function does.

Paul Graham in “Ansi Lisp”

By that definition, would’nt a pointer to member function that refers to a member variable of a object also be a closure, since its referring to a variable defined in the lexical scope of the class. Thinking about this, I googled it and looked about some comparisons of how closures are done. I realized that the code in the 2nd cut of my solution in this post was a a sort of closure. If you look at the definition of the source code of the nested class,

    template<typename SequenceIterator>
    struct find_max_sum_range_helper
    {
    public:
        find_max_sum_range_helper
            ( typename SequenceIterator::value_type &max_so_far_
            , typename SequenceIterator::value_type &max_ending_here_
            , std::pair<SequenceIterator, SequenceIterator > &p_
            , typename SequenceIterator &current_)
            : max_so_far(max_so_far_)
            , max_ending_here(max_ending_here_)
            , p(p_)
            , current(current_)
        { /* Do nothing else */}

        void operator()(typename SequenceIterator::value_type val){
            if(max_ending_here==0){
                p.first = p.second = current;
            }

            max_ending_here =
                std::max<typename SequenceIterator::value_type>(max_ending_here + val, 0);

            if (max_ending_here > max_so_far){
                max_so_far = max_ending_here;
                p.second = current;
            }
            //increment the current operator;
            ++current;
        }

    private:
        typename SequenceIterator::value_type &max_so_far;
        typename SequenceIterator::value_type &max_ending_here;
        typename std::pair<SequenceIterator, SequenceIterator> &p;
        SequenceIterator &current;
    };

find_max_range_helper refers to variables that are defined outside its lexical scope in find_max_range2, using C++ references as shown below.

...
        typename SequenceIterator::value_type &max_so_far;
        typename SequenceIterator::value_type &max_ending_here;
        typename std::pair<SequenceIterator, SequenceIterator> &p;
        SequenceIterator &current;
...
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: