Exposing only a single method of a class to another class but having it inaccessible everywhere else

124 Views Asked by At

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.
  }
};
0

There are 0 best solutions below