Introduction
The purpose of this class is :-
- Defines template for automatic sequential ID numbers.
- Useful for implementing IDs.
- Supports multiple unique ID categories.
- The values are guaranteed to be sequential in each category.
Interface
template <typename TValue, typename TCategory>
class unique_value
{
public:
typedef TValue value_type;
typedef TCategory category_type;
unique_value();
operator const value_type&() const;
static const value_type& get_counter();
protected:
value_type m_value;
}
Usage
- Use as a numeric data type in the class you want to have unique IDs.
- The category is determined of both
TValue
and
TCategory
. - It's recommended to create a
typedef
and to use it for all your IDs unless you have a reason not to do so. - Use
INIT_UNIQUE_CAT
and INIT_UNIQUE
macros to initialize categories
INIT_UNIQUE(long);
typedef unique_value<long> unique_long;
class some_data_class
{
unique_long ID;
int data1;
int dataN;
}
class different_category_data_class;
INIT_UNIQUE_CAT(long, different_category_data_class);
class different_category_data_class
{
unique_value<long, different_category_data_class> ID;
}
foo()
{
some_data_class data_object;
different_category_data_class another_object;
cout << data_object.ID << another_object.ID;
}
Code listing
#if !defined(__UNIQUE_VALUE__)
#define __UNIQUE_VALUE__
typedef int default_unique_category;
template <typename TValue, typename TCategory=default_unique_category>
class unique_value
{
public:
typedef TValue value_type;
typedef TCategory category_type;
unique_value():m_value(m_counter){m_counter++;};
operator const value_type & () const {return m_value;};
static const value_type& get_counter() {return m_counter;}
protected:
value_type m_value;
private:
unique_value (value_type&);
void operator= (value_type&);
static value_type m_counter;
};
#define INIT_UNIQUE(t_value) \
INIT_UNIQUE_CAT(t_value, default_unique_category)
#define INIT_UNIQUE_CAT(t_value, t_category) \
unique_value<t_value, t_category>::value_type \
unique_value<t_value,t_category>::m_counter=0
#endif
History
- Created - 6 May 2001
- Added multithreading support - 6 June 2001
- Removed multithreading support - 12 Sept 2001
Conclusion
I'd be glad if somebody uses this class. If you do, please mail me
at LOXmith@abv.bg. I had to remove multithreading support. The reason is
that you can't achieve platform dependent behaviour using platform independent ways. If you still need
multithreading - see the discussion below.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.