c++function entities — 2nd class citizens@@

Compared to java, I feel c++ is more flexible, “creative” and “loose” with functions; c++ weaves functions more into its rich syntax; and c++ apps rely more heavily on passable function entities. Any algorithm (any trivial body of code) can be passed around like a variable or object.

Inside the computer, a function (like objects) occupies a chunk of memory in “text” section, so it’s reasonable to pass its address to where it’s needed. C++ lets your *package* algorithms into passable function entities. These function entities are often stateless[2]. Consider functional programming. I call these 2nd-class citizen objects because they normally do not have state, variables, virtuals etc.

(Java Threads also should not but often have state.)

Java has interfaces and Method objects. C++ has func pointers and functor objects. Both designs are powerful, widespread and proven.

[2] functors are almost always pbclone in STL. Some functors are stateful — (beside generators) Dinkumware’s hash tables have hashing traits/policies as state in the hashing functors. See separate blog post.

http://www.newty.de/fpt/fpt.html#callconv shows some func ptr syntax examples —

someObject.someMethodReturningAFunctor()(arg1, arg2); // not the number of () pairs
(instance1.*pt2Member)(12, ‘a’, ‘b’);

(*this.*pt2Member)(12, 'a', 'b');     
(instance2->*pt2Member)(12, 'a', 'b');  

(*(someComplexExpressionReturningFuncPtr))(arg1, arg2)


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

WordPress.com 徽标

您正在使用您的 WordPress.com 账号评论。 登出 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 登出 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 登出 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 登出 /  更改 )

Connecting to %s