1

Consider the following class representing an integer parameter with upper and lower limits:

class Parameter
{
protected:
    int value;
    int minval;
    int maxval;
};

I have a list of Parameter objects. Sometimes, a Parameter's minval/maxval will be the value of another Parameter in the list. Other times, they will just be integer literals. From what I understand, I can make minval/maxval either a reference to another Paremeter's value, or an integer literal, but not both, because int& != int.

How can I get around this?

  • What should happen if the `value` of one `Parameter` changes, changing the `maxval` of some other `Parameter`, and now that second `Parameter` has an invalid `value`? – Nathan Pierson Aug 19 '21 at 16:10
  • 1
    First, I'd define a union type "IPU" consisting of an int and a Parameter*. Then, I'd adopt the convention that when you want to use this type as if it were an int, make the Parameter* NULL; that way, given an IPU, you can easily decode it into an integer, e.g., "val = ipu.parameter == NULL ? ipu.int : ipu.parameter". Make sense? – Mark Lavin Aug 19 '21 at 16:13
  • If they are `const` references, they can be initialised in the constructor - and can refer to literals. The trick will be writing the set of constructors needed (with initialisation lists) to do the initialisation. If you need to somehow reseat the references, create a new object (since references can only be initialised when created, and never reseated). – Peter Aug 19 '21 at 16:19
  • "_I have a list of Parameter objects. Sometimes, a Parameter's minval/maxval..._" does **sometimes** mean within one list or for each parameter type a different list? – Erdal Küçük Aug 19 '21 at 16:30
  • What happens if/when there are circular references? – Pablo H Aug 19 '21 at 16:58

1 Answers1

3

This is hard to answer without more information, but if you want the same class to have members that can either be an int or refer to an int that sounds like a use case for an std::variant, that is

class Parameter
{
protected:
    int value;
    std::variant<int, int*> minval;
    std::variant<int, int*> maxval;
};

Note that a pointer type is necessary here because variants cannot hold references.

jwezorek
  • 8,592
  • 1
  • 29
  • 46