block in C++

In my previous posts on block, I tried to understand what block is, how it is different from function pointer, what it is supposed to solve, and so on.
Here are the posts.

It looks like that it is influence from JavaScript. ( Java also? )
Mozilla provides very good reference on Javascript from its Netscape era, and

var multiply = new Function("x", "y", "return x * y");
var theAnswer = multiply(7, 6);

As you can see, it is very similar to the block in Objective-C.

Then how does it look like in C++?
MSDN has a good example.

class Functor
    int operator()(int a, int b)
        return a < b;

int main()
    Functor f;
    int a = 5;
    int b = 7;
    int ans = f(a, b);

In short, you should declare/define a class, because function object is an object.
Also, because it should have a shape of a function. In other words, the function object will have this shape when used.

instance_name( … )

So, an operator, () should be declared and defined.

In C++, fucntion object is created as OBJECT + operator().

Same concept, different way of implementation. Isn’t it interesting?

ADDED : Well, I’m sorry. C++ also supports lamda functions. Lamda function is more like function object in JavaScript and Objective-C. What is interesting is that Objective-C doesn’t differentiate lamda function and function object. They share the same syntax basically. However, in C++, they both have their own syntax. I like function object style more, because it is clearer, but lamda function style has its own virtue. MSDN also has good examples on lamda function and function object. “Lamda Expressions in C++”


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your 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: