For Programmers: Free Programming Magazines  


Home > Archive > Scheme > January 2006 > C++ closure example









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author C++ closure example
H.

2006-01-16, 9:57 pm


> Not especially. Objects help, and in C++ one can overload the
> function-calling operator.


>
> class adder {
> int i;
> public:
> adder(int n): i(n) {}
> operator()(int n) {return n+i;}
> };
>
> ...
>
> adder plus_7(7);
>
> std::cout << plus_7(42) << std::endl << plus_7(18) << std::endl;
>
>
> Still clumsy compared to something that really has closures like Lisp,
> ECMAscript, etc.


When I try to compile this, I get an "ISO C++ forbids declaration of
'operator()' with no type" error.

It seems like a good example I'd like to play around with more, if it's
a valid one and I can get it to work.

Thant Tessman

2006-01-16, 9:57 pm

H. wrote:
>
>
>
>
> When I try to compile this, I get an "ISO C++ forbids declaration of
> 'operator()' with no type" error.
>
> It seems like a good example I'd like to play around with more, if it's
> a valid one and I can get it to work.


The return type is missing. Without actually having tried to compile
something, I would guess it should be:

int operator()(int n){return n+i;}

You can actually build quite sophisticated function object systems in
C++ by leveraging templates and many other tricks, but they always fall
short of being satisfactory. Issues with memory management, argument
calling conventions, etc. never really go away in C++.

-thant

--
We have now sunk to a depth at which restatement of the obvious is the
first duty of intelligent men. -- George Orwell (attributed)
Bruce Stephens

2006-01-17, 9:57 pm

"H." <hbe123@gmail.com> writes:

[...]

> When I try to compile this, I get an "ISO C++ forbids declaration of
> 'operator()' with no type" error.


Oops, sorry. Should be int operator()..., obviously.

> It seems like a good example I'd like to play around with more, if
> it's a valid one and I can get it to work.


This kind of thing (creating objects which provide an operator()) is
well known in C++, and there's some convenience functions in the
standard library. More in boost, of course:
<http://www.boost.org/libs/libraries...unction-objects>.

It's not really lisp, or scheme, or closures. But if you're using C++
for some other reason (because you're maintaining a system already
written in it, for example), it can be useful to know what wacky
things are possible, even if you decide not to use many of them.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com