I am writing a library, all classes of which are in one namespace. I need to define a utility function that will be called only by the classes of my library and will never be called outside of it. But at the same time I can not put it in anonymous namespace or mark it as static because its calling classes are in different translation units.

In general, an analogue of C # internal sought, but for C ++. What do you advise?

I am also ready to listen to criticism of the justification of such a cover-up as a whole. For the service function cannot violate the integrity of any class and its concealment is rather a matter of good style.

  • 2
    In general, it is customary to do classes in c ++. And, accordingly, private methods. - KoVadim
  • You can simply insert it into the private static of each class that calls it and duplicate the definition in each file, of course this is the Chinese version, plus the fact that it is extremely simple. Before you copy it is necessary to test it completely. - igumnov

2 answers 2

  • Either mark it as private static in a special class, and give other classes access through a friend, or just create a special namespace called detail and place this function in it.

Boost, for example, uses the second option.

  • As for justification, there really are such functions that it makes sense to reuse, but only in the context of a module. That is, if you know for sure that this function is forbidden to be used from the outside, then, strictly speaking, from detail in this case can not go anywhere.

Another thing is that you can usually turn this kind of function into quite solid solid helper methods that can be made public and tested from another module (if there is a need for it).

  • internal in C # is only useful in the context of working with assemblies, so naturally, C ++ does not have its direct equivalent.
  • Does the option with detail restrict access from the outside? I mean, a third-party developer can use the functions of their namespace. - fogbit
  • one
    @fogbit Maybe, but should not under the contract. And what happens in case of breach of contract, in general, we should not care. - Costantino Rupert
  • Those. is it just an arrangement of library developers? - skegg
  • IMHO in this discussion, everyone understands that with a strong desire, you can call any (even static) function. - avp 2:51 pm

I'm afraid the usual function is so easy to hide.

You can declare it as a private static method of some class, then in this class specify friendly functions and classes from which it can be called. Like that:

 #priv_func.h class B; void ff(); ..... Здесь список объявлений всех друзей class AA { friend void ff(); friend class B; ........ private: static void priv_func() { std::cout << "Private" << std::endl; } }; 

All this is made in the form of a header, which is then inserted where necessary.

The function is very simple to call.

 AA::priv_func();