mercredi 7 janvier 2015

C++: what's the usage of declaring a function inside another function?

Stanley Lippman's "C++ primer" mentioned, in page 234 that



Ordinarily, it is a bad idea to declare a function locally. However, to explain how scope interacts with overloading, we will violate this practice and use local function declarations.




...
void print(const string &);
void print(double); // overloads the print function
void fooBar(int ival)
{ ...
// bad practice: usually it's a bad idea to declare functions at local scope
void print(int); // new scope: hides previous instances of print
print(ival); // ok: print(int) is visible
print(3.14); // ok: calls print(int); print(double) is hidden
}


Nevertheless, which situation it might make sense to do so, declaring a function inside the body of a function?


I recall similar code in Scheme:



(define (PowerSet set)
(if (null? set) '(())
(let ((PowerSetAfterHead (PowerSet (cdr set) ) ))
(append PowerSetAfterHead
(PowerSet (cdr set) )
(map
(lambda (subset)
(cons (car set) subset
)
)
(PowerSet (cdr set) )
)
)
)
)
)


Is it normally used to hide from misuse of a "local function" that intends for the outer function's usage only? something like internal class? Or is it useful in some design patterns?


Aucun commentaire:

Enregistrer un commentaire