Function within a Function in C++

I have been coding in C++ for a number of years. Only recently did I find out that there is an indirect way to write a function within a function. I have found myself using this little workaround more and more recently. When coupled with the use of a static variable within a function, the ability to have “Everything In Its Right Place” i.e. avoid unnecessary functions and variables in the global namespace, is particularly appealing to my inner code nazi.

The below code snippet shows an example…

Note

– I have only tested the code snippet below for compilation using Visual Studio
– Visual Studio’s debugger does not allow you to “watch” spndI when execution is inside the function NodeIsOfSameTypeAsIButNotI

– I have formatted the code for the narrow width afforded this blog! So the example looks more verbose than it would otherwise be, and the blogger may mangle some of the code when it is posted (causing me to re edit the post over and over until google gets it right)

struct CNode
{
// shell struct to enable code compilation
double GetLongitude() const {return 0;}
double GetLatitude() const {return 0;}
double GetType() const {return 0;}
};
template class CSomeClassHoldingNodesForFastFinding
{
public:
typedef bool(*NodeCanBeClosest)(const T*);
template inline T* FindClosest
(
double dblLongitude,
double dblLatitude,
NodeCanBeClosest pNodeCanBeClosest
)
{
return NULL; // Really return a T* not Null
}
};
void FindClosestNodePairsAndDoSomethingWithThem
(
vector& rgpnd,
CSomeClassHoldingNodesForFastFinding* pFastFindNodes
)
{
static CNode* spndI = NULL;
for (size_t nNodeI = 0; nNodeI != rgpnd.size(); nNodeI++)
{
spndI = rgpnd[nNodeI];
struct Func
{
static bool NodeIsOfSameTypeAsIButNotI(const CNode* pnd)
{
return
pnd != spndI
&&
pnd->GetType() == spndI->GetType();
}
};
CNode* pndJ = pFastFindNodes->FindClosest
(
spndI->GetLongitude(),
spndI->GetLatitude(),
&Func::NodeIsOfSameTypeAsIButNotI
);
// .. Do something with spndI and pndJ
}
}
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published.