0

I wonder if there is some non-ugly way to expose only one method of a class to only one class.

I come up with this solution and wonder if there is any other better (shorter) way to achieve the same?

class BarMethodGuard {
private:
  friend class Foo;
  friend class Bar;
  class Guard {
  public:
    static Guard get() {
      static auto singleton = new Guard();
      return *singleton;
    }
  private:
    Guard() {}
  };
};

class Bar {
public:
  void bar(BarMethodGuard::Guard) {}
};

class Foo {
public:
  Foo() {
    Bar().bar(BarMethodGuard::Guard::get());  // This would compile.
  }
};

class Foo2 {
public:
  Foo2() {
    Bar().bar(BarMethodGuard::Guard::get());  // This won't compile.
  }
};
Evg
  • 25,259
  • 5
  • 41
  • 83
  • [passkey idiom](https://arne-mertz.de/2016/10/passkey-idiom/) is indeed one good way to handle that. (even if your singleton is not needed). – Jarod42 Nov 14 '22 at 16:20
  • The need for `friend` functions or classes, is almost always a heavy indicator for a bad class hierarchy design. You should replace that with static or dynamic polymorphism. Get some better ideas [here](https://stackoverflow.com/questions/27492132/how-can-i-remove-refactor-a-friend-dependency-declaration-properly). – πάντα ῥεῖ Nov 14 '22 at 16:25

0 Answers0