We're experimenting with having bounded primitive types
in our project where we can check that instances of derived classes have a data value within valid range (min
and max
member variables, protected in base class
) for that derived class
.
My question is, is there a way I can statically initialise the derived class's min
and max
variables, just once per derived class
, rather than every time I instantiate the derived class
.
In C#
this would be in a static initialisation block, but I'm not sure how to do it in C++
.
I know I could initialise them in the derived class constructor
, but this seems wasteful to do it each time.
I think I'm looking for abstract data members, declared in a base class, but subequently defined statically in derived classes.
class BoundedFloat
{
public:
BoundedFloat(const float v) : Value(v) {}
// some common methods that use Min and Max
// prefer to implement in base class rather than in each derived class
bool withinBounds();
bool breachedLowerThreshold();
bool breachedUupperThreshold();
protected:
const float Min;
const float Max;
float Value;
}
bool BoundedFloat::withinBounds()
{
return ((Value >= Min) && (Value<= Max));
}
bool BoundedFloat::breachedLowerThreshold()
{
return (Value < Min);
}
bool BoundedFloat::breachedUupperThreshold()
{
return (Value > Max);
}
class Temperature : public BoundedFloat
{
public:
Temperature(const float v) : BoundedFloat(v) {}
// seems wasteful to do this each time, when min and max only need
// initialised once per derived class
// Temperature(const float v) : BoundedFloat(v, -40.0f, 80.0f)
// statically initialise Temperature's Min and Max in base class here somehow?
private:
// I know this is wrong, but it indicates the functionality I'm looking for.
override static float Min;
override static float Max;
}