Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
Arpita Korwar Avatar asked Jun 24 '26 19:06

Arpita Korwar


1 Answers

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

template <std::size_t N>
struct NumberModuloN
{
    /*..*/
};
like image 91
Jarod42 Avatar answered Jun 27 '26 10:06

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!