How to make a friend function an internal link

I need to make sure that a C ++ function declared as a friend of a particular C ++ class has an internal binding.

The reason I need a function to be a friend is because it needs access to a private member of this class, a private member that caches the result of the function.

The reason that a function must be non-member (or at least not an instance member) of the same class is because other code should be able to use a non-member function pointer. Refactoring it will be too expensive.

The reason I need to have an internal connection is because there will be many of these functions, and on AIX, when too many of them cause a TOC overflow error when binding. This can be overcome with the -bbigtoc linker switch, but I try to avoid this for now.

In addition, I would really like to save the class declaration in the header file, but put this function in the .cxx file containing the implementation.

To summarize, right now I have something like this:

 class Foo { private: mutable Qux cachedBarResult; // ... more code here ... public: friend const Qux & Bar(const Foo &); }; const Qux & Bar(const Foo & foo) { if (foo.cachedBarResult.isEmpty()) { foo.cachedBarResult = _worker_Bar(foo); } return foo.cachedBarResult; } static Qux _worker_Bar(const Foo & foo) { // real Bar work } 

I want Bar have an internal connection. It can be done?

+4
source share
1 answer

Yes, you just have to declare a prototype of a static function before telling a friend.

 class Foo; static const Qux & Bar(const Foo & foo); class Foo { private: mutable Qux cachedBarResult; // ... more code here ... public: friend const Qux & Bar(const Foo &); }; static const Qux & Bar(const Foo & foo) { if (foo.cachedBarResult.isEmpty()) { foo.cachedBarResult = _worker_Bar(foo); } return foo.cachedBarResult; } 
+6
source

Source: https://habr.com/ru/post/1441867/


All Articles