'Any way to add custom type modifiers to either c# or c++?

I want to be able to use this syntax here:

public enclosed int num = {0, 5, 10};

this code would clamp the int num from 0 to 10, with a starting value of 5.

you could make a class that handles this, but it would be a lot of extra effort for a sort of convoluted solution, and I'm wondering if there is a way to somehow to do it just in a variable declaration, sort of like declaring an unsigned int, I want to be able to declare an enclosed int.



Solution 1:[1]

No, this is exactly what classes and structs are for, so that you can create your own types with these sorts of behaviors. But these are compiled languages, so the syntax is fixed. In C++ you might be able to do something using macros, but that's a preprocessor thing.

Solution 2:[2]

I got pretty close :P

public class enclosed<T> {
    private T min {get;}
    private T max {get;}
    private T val {get;}
    
    public enclosed(T min, T val, T max)
    {
        ...
    }
}

Now you can use it like this:

public enclosed<int> num = new(0, 5, 10);

vs

public enclosed int num = {0, 5, 10};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John V
Solution 2 tymtam