sans-hubris
06-09-2002, 09:50 AM
Allow me to make a proposal to you. Many languages allow you to nest functions within other functions, except for C/C++! Function nesting is such a cool feature, isn't it?
For example, in Scheme, you can do the following:
(define powers-seq
(lambda (power)
(lambda (x)
(letrec
((power-list
(lambda (x lst)
(if (zero? x)
lst
(power-list (- x 1)
(if (null? lst)
(cons 1 lst)
(cons (* power (car lst)) lst)))))))))))
(define power3 (powers-seq 3))
;Now I have an infinite sequence of the powers of three.
Would it not be nice to be able to do something like this in C/C++?
Well, we can do something like this in C++, but there is not much we can do about C, for now. In C++, we need to take advantage of operator overloading of C++ classes. More specifically, we need to overload the () operator. The idea is that we will have objects that behave like functions (which will now be referred to as functors), and since you can have other objects within functions, you can embed other functors.
class fooFunctor;
class barFunctor;
fooFunctor foo;
barFunctor bar;
class fooFunctor
{
public:
void operator() (int parm1, int parm2) //This should be the only public function.
{
bar(parm1+parm2, parm1*parm2);
}
};
class barFunctor
{
public:
void operator() (int parm1, int parm2)
{
cout << parm1 << " " << parm2 << endl;
}
};
int main(void)
{
foo(5,9);
return 0;
}
I'll leave the creation of a powers_seq functor as an exercise for you to do.
For example, in Scheme, you can do the following:
(define powers-seq
(lambda (power)
(lambda (x)
(letrec
((power-list
(lambda (x lst)
(if (zero? x)
lst
(power-list (- x 1)
(if (null? lst)
(cons 1 lst)
(cons (* power (car lst)) lst)))))))))))
(define power3 (powers-seq 3))
;Now I have an infinite sequence of the powers of three.
Would it not be nice to be able to do something like this in C/C++?
Well, we can do something like this in C++, but there is not much we can do about C, for now. In C++, we need to take advantage of operator overloading of C++ classes. More specifically, we need to overload the () operator. The idea is that we will have objects that behave like functions (which will now be referred to as functors), and since you can have other objects within functions, you can embed other functors.
class fooFunctor;
class barFunctor;
fooFunctor foo;
barFunctor bar;
class fooFunctor
{
public:
void operator() (int parm1, int parm2) //This should be the only public function.
{
bar(parm1+parm2, parm1*parm2);
}
};
class barFunctor
{
public:
void operator() (int parm1, int parm2)
{
cout << parm1 << " " << parm2 << endl;
}
};
int main(void)
{
foo(5,9);
return 0;
}
I'll leave the creation of a powers_seq functor as an exercise for you to do.