Subscribe to RSS

C++: Alias namespaces to reduce code clutter

Back to MainPage, back to ProgrammingStuff

When using boost, or other big libraries that use namespaces to logically organize themselves, you can quickly find yourself staring at a page awash with namespace specifiers, rather than the core algorithms and ideas you're focusing on.

One solution is to issue a number of blanket statement for this translation unit:

using namespace std;
using namespace boost::interprocess;
using namespace boost::regex;

This can lead to conflicts between your local code, and all the imported types.

Another technique is to add using clauses for each typename, generally at the start of each function.  This has the advantage of being very specific, but it can increase code clutter, if taken too far.  Use when appropriate.

The better solution, in some cases, is to use namespace aliasing, as:

namespace bipc = boost::interprocess;
namespace breg = boost::regex;

I'd steer clear of defining these at a global level, it's sufficient to add these near the top of your implementation  file (.cpp).

Here's a quick example (it's not the best, but you get the idea).  Code lifted and modified for illustrative purposes from "Synchronization mechanisms" in the Boost 1.38 Interprocess librarys documentation.

#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>

int main ()
{
try{
//Erase previous message queue
boost::interprocess::message_queue::remove("message_queue");

//Create a message_queue.
boost::interprocess::message_queue mq
(boost::interprocess::create_only //only create
,"message_queue" //name
,100 //max message number
,sizeof(int) //max message size
);

//Send 100 numbers
for(int i = 0; i < 100; ++i){
mq.send(&i, sizeof(i), 0);
}
}
catch(boost::interprocess::interprocess_exception &ex){
std::cout << ex.what() << std::endl;
return 1;
}

return 0;
}

becomes:

#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>

namespace bi = boost::interprocess;

int main ()
{
   try{
      //Erase previous message queue
      bi::message_queue::remove("message_queue");

      //Create a message_queue.
      bi::message_queue mq
         (bi::create_only               //only create
         ,"message_queue"           //name
         ,100                       //max message number
         ,sizeof(int)               //max message size
         );

      //Send 100 numbers
      for(int i = 0; i < 100; ++i){
         mq.send(&i, sizeof(i), 0);
      }
   }
   catch(bi::interprocess_exception &ex){
      std::cout << ex.what() << std::endl;
      return 1;
   }

   return 0;
}

Personally, I use whatever works and results in readable code.

Back to MainPage, back to ProgrammingStuff

Edited on Sat, May 2, 2009 at 4:04 a.m.