C++ does not support nested function. Say I have function a and b, I want to guarantee that only a can call b, and nobody else can, is there a way of doing so?
4 Answers
There are multiple ways of doing this (none are 100% bulletproof, someone can always edit your source files), but one way would
Put the function inside a class, make it private, and make the functions that you want to have the ability to call it "friends."
Assuming you want function
ato be callable by functionbbut no one else, another way would be to putaandbin their own source file together and makeastatic. This way,awould only be visible to entities in the same source file, butbwould be visible to everyone who had it's signature.
Or 3. If you can use lambdas (i.e. your compiler supports this feature of C++11):
void a() { auto f = []() { /* do stuff */ } f(); } 4 Comments
The passkey idiom.
class KeyForB{ // private ctor KeyForB(){} friend void a(); }; void a(){ b(KeyForB()); } void b(KeyForB /*unused*/){ } Comments
No, but you can always create a function-level class. For example:
void MyFunction() { class InnerClass { public: static void InnerFunction() { } }; InnerClass::InnerFunction(); InnerClass::InnerFunction(); // ... }; 3 Comments
InnerFunction is a template; (2) anytime this would work, you can/should just use a lambda instead; (3) typically you break code up into functions so that you can move it out of line. Answerers/voters here naturally assume that you want to limit the callers of an ordinary out-of-line function, not (as here) simply take that function and in-line it into the scope where it's used. (This also means this approach fails if there are two callers.)MyFunction itself can be made a template and then the template parameter used inside InnerFunction, which may or may not be enough in a specific situation.