Name Generator        

About the Name Generator

The following class is based on a forum thread.

This class helps with giving unique names to your Ogre objects (and other objects as well).

Source Code

NameGenerator.h

#ifndef NAME_GENERATOR_H
#define NAME_GENERATOR_H
#include <string>
#include <cstdint>

/**
 * \brief   A utility class to generate unique names.
**/
class NameGenerator
{
public:

   /**
    * \brief   Gets the next unique name.
   **/
   static std::string Next();

   /**
    * \brief   Gets the next unique name for a given prefix.
   **/
   static std::string Next(const std::string& prefix);

   /**
    * \brief   Counts the number of unique auto-generated names.
   **/
   static size_t Count();

   /**
    * \brief   Counts the number of names generated for a given prefix.
    * \param   prefix   The prefix of the generated names.
   **/
   static size_t Count(const std::string& prefix);
private:
   NameGenerator();
   ~NameGenerator();

   typedef std::map<std::string, uint32_t> NameCountMap;
   static NameCountMap s_nameCount;
};
#endif


NameGenerator.cpp

#include <sstream>
#include "NameGenerator.h"

const std::string DEFAULT_NAME_PREFIX = "AutoGeneratedName";
NameGenerator::NameCountMap NameGenerator::s_nameCount;
//---------------------------------------------------------------------
NameGenerator::NameGenerator()
{
}
//---------------------------------------------------------------------
NameGenerator::~NameGenerator()
{
}
//---------------------------------------------------------------------
std::string NameGenerator::Next()
{
   return Next(DEFAULT_NAME_PREFIX);
}
//---------------------------------------------------------------------
std::string NameGenerator::Next( const std::string& prefix )
{
   if (s_nameCount.count(prefix) == 0)
   {
      s_nameCount[prefix] = 0;
   }
   std::stringstream ss;
   ss<<prefix<<"_"<<s_nameCount[prefix]++;
   return ss.str();
}
//---------------------------------------------------------------------
size_t NameGenerator::Count()
{
   size_t count = Count(DEFAULT_NAME_PREFIX);
   return count;
}
//---------------------------------------------------------------------
size_t NameGenerator::Count( const std::string& prefix )
{
   size_t count = (s_nameCount.count(prefix) == 0)?0:s_nameCount[prefix];
   return count;
}

Usage

std::string autogenerated_name = NameGenerator::Next();      // Generates (from the above code) 'AutoGeneratedName_x', where x is a number
std::string new_entity_name = NameGenerator::Next("Entity"); // Generates 'Entity_x', where x is a number

// Usage example with Ogre:
Ogre::Entity* Mass = mSceneMgr->createEntity(NameGenerator::Next("Entity"), "lightsphere.mesh");

As this class has only static functions, you don't need to create an instance of it.