Being friendly without being a slut

So you’ve got some sort of problem that you cannot solve without friendship. Being the design oriented developer you are you know that this level of coupling is pretty major and best to be avoided, but you simply can’t avoid it; you absolutely need access to some internal functionality to be exposed to special classes. Knowing how bad it is, and not wanting to encourage developers working on your friends to start molesting you freely, you want to show just enough skin to get the job done. But C++ doesn’t provide any way to do this… or does it?

#include <iostream>

struct almost_friendly
{
  struct funktor
  {
    funktor(almost_friendly * t) : this_(t) {}

  private:
    void operator() ()
    {
      this_->something_private();
    }
    almost_friendly * this_;

    friend struct has_special_access;
  };

  funktor fun;

  almost_friendly() : fun(this) {}

private:
  void something_private() { std::cout << "Only has_special_access can call this.\n"; }
};

struct has_special_access
{
  void fun() { almost_friendly().fun(); }
};

int main() { has_special_access().fun(); }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: