Search code examples
c++moduleencapsulation

Friend class with only static member functions as a friend module in c++?


I have a class (say MyClass) and functions that take instances of MyClass as arguments. The functions need to access private members of MyClass. The members are private because users of MyClass don't need to be know about the members. However, I don't want to make the functions members of MyClass because the functions should take several MyClass instances as arguments and the arguements are treated symmetrically. I don't want to deal "this" object specially.

If there were a kind of module system so I could declare a module containing the functions as a friend of MyClass, I would be happy. But there is no such things in C++. One way is to make a friend class and make the functions static members of the class. However, many people don't recommend the way (eg. Namespace + functions versus static methods on a class) because class is not intended for such use.

Any design solution for this case?


Solution

  • namespace is the currently relevant feature. But isn't possible to get a friend namespace, no more that it is possible to template a namespace or pass a namespace as a template parameters, two common cases where struct with only static members are commonly used as a work around. So there is a good precedent of using a struct. There is at least another reason to use a struct of static members instead of a namespace: a namespace is open to addition while a struct is closed. And that aspect alone could be also a justification of using a struct instead of a namespace for friend.