Arpita Korwar
Arpita Korwar

Reputation: 33

In C++, can we create a class for each integer?

I need to create a class NumberModuloN. For each positive integer N, there should be a distinct class. What is the most elegant way to do this?

Here are some more details: The data consists of a single integer in the range 0 to N-1. It can be modified using some public operator overloading methods like +, *, -, ++, etc.

The idea is that, for example, an object of numberModulo100 has no business with any object of numberModulo99. Adding, subtracting, multiplying them won't make sense.

One thing I came up with was to use a constant variable for N that gets initialised in the constructor. Here is a reference to constant variables https://stackoverflow.com/a/18775482/15360444. But the problem is that, now, every binary operator method would have to check if the Ns of the two operands match before proceeding. It is not very elegant.

I need something similar to a C++ template which gives a different class for each data type. I just need a different class for each positive integer.

Upvotes: 3

Views: 434

Answers (1)

Jarod42
Jarod42

Reputation: 217810

You might use non-type parameter in template, so, something like:

template <std::size_t N>
struct NumberModuloN
{
    /*..*/
};

Upvotes: 3

Related Questions