You are here:

C++/c++-data types

Advertisement


Question
How to make user defined data type with its own range(e.g. 1 to 5) in c++ ?

Answer
A simple way is to use an enum:

enum values_t { ONE=1, TWO, THREE, FOUR, FIVE };


If you want to support more operations on the type (for example via overloaded operators), write a class:

struct one_to_five
{
   one_to_five( unsigned int v = 1 ) { value = 1 + (v-1)%5 ; }
   operator int () const { return value ; }
   // etc.

   private: int value ; // in the range one to five
};

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.