3

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.

1 Answers1

3

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

template <std::size_t N>
struct NumberModuloN
{
    /*..*/
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Aside: You can also specialise this for certain values, e.g. `template <> struct NumberModuloN<0>;` (an incomplete type) to prevent use of mod 0 – Caleth Mar 09 '21 at 13:02
  • @Caleth: `static_assert(N != 0);` seems enough here (or `requires (N != 0)`). But in fact act as template with type parameters. – Jarod42 Mar 09 '21 at 13:05
  • It works. This is exactly what I wanted. Thank you! – Arpita Korwar Mar 18 '21 at 17:07