Archive for October, 2011

Being friendly without being a slut

Posted in Uncategorized on October 6, 2011 by Crazy Eddie

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