lundi 2 octobre 2023

Named anonymous Namespace pattern

I'm pretty new to C++, but after refactoring a class that was almost entirely static methods into member functions in a named namespace, I belatedly realised you can add named namespaces into an anonymous one, that you can then reference in internal calls, avoiding collisions and keeping them internally linked:

namespace MyNamespace {

  namespace {
    namespace NS {
      int y = 1;
      // other internals...
    }
  }

  int getY(){
    return NS::y;
  }

}

A pattern I personally liked, that lead me to add a macro for extra clarity:

#define INTERNAL_NS namespace { namespace NS {
#define END_INTERNAL }}


namespace MyNamespace {

  INTERNAL_NS
    int y = 1;
    // other internals...
  END_INTERNAL


  int getY(){
    return NS::y;
  }

}

This feels like an expressive way to avoid static globals and effectively define a "private" namespace. However, before I adopt this pattern throughout the codebase and dig myself a hole I might later regret, I wondered what others thought of this approach? Any obvious, or non-obvious downsides...?

Aucun commentaire:

Enregistrer un commentaire