This post is part of a regular series of posts where the C++ product team here at Microsoft answers questions we have received from customers. The questions can be about anything C++ related: Visual C++, the standard language and library, the C++ standards committee, isocpp.org, CppCon, etc. Today’s Q&A is by Herb Sutter.
Reader @thesamhughescom recently asked:
Has there ever been a consideration for allowing individual private functions to whitelist other classes or functions to call them? Similar to the per class friend method, I was thinking you could annotate a function with
[[friend void foo(int)]]or
[[friend class baz]]just an idea, I wouldn’t know where to get started on writing my own proposal, thanks Sam
There are occasionally proposals, but
friend itself should be used very rarely so there’s not a lot of motivation to encourage it.
One technique you can use today is to provide a set of friend helper types, each of which provides specific access to a given subset of things and can name its own friends, be handed out to callers, etc. That’s a flexible form of access control that works for granting different degrees of friendship statically to a set of types, granting access to some parts of the class’s interface dynamically to a set of callers, and so on.
But the last part of your question is the easiest, and perhaps the most important:
I wouldn’t know where to get started on writing my own proposal
Always (always, always, …) start with use cases. Write two or three concrete examples of the kind of code you want to write (initially pseudocode), explain clearly why you want to express it that way, and show the workarounds if any that are available for approximating it today. Compelling examples serve two major purposes: they motivate the feature (answer “why” questions like why have the features), and they also provide reference points to guide the feature’s design (answer “what” and “how” questions like what things the feature must be able to express and how it should be able to be used).
If you have any question about C++ in general, please comment about it below. Someone in the community may answer it, or someone on our team may consider it for a future blog post. If instead your question is about support for a Microsoft product, you can provide feedback via Help > Report A Problem in the product, or via Developer Community.