jeudi 23 mai 2019

c++: enforce compilation error if function A is not called before function B

I'm designing a class Parameter to hold a parameter that can be read from an external resource (a configuration file, a server, ecc).

My class does not allow to set the parameter value in the constructor, but provides an interface to set and access it through the methods SetValue and GetValue, respectively. Between the creation of a Parameter object and the call to the method SetValue on that object, the parameter is hence in an "undefined" state. I would like to prevent the user of the class to access the value of the parameter if it is undefined.

One way to achieve it, for instance, is using a boost::optional and raise an error if an attempt to access the value is done before calling the setting function:

class Parameter{
public:
    void SetValue(double val){ value_ = val; }

    double GetValue() const {
        if(!value_)
            // raise an error
        return *value_;
    }

private:
    boost::optional<double> value_;
};

This way we can achieve the following behaviour:

Parameter a;
a.SetValue();
a.GetValue();     // ok

Parameter a1;
a1.GetValue();    // runtime error, a1 is undefined

Now, I would like to raise an error at compile-time when the value is undefined. I already considered the option to modify my interface and allow the user to set the value in the constructor and nowhere else (so that the parameter is always in a consistent state), but it does not really fit very well the rest of my design.

So I was wondering if there is a way to achieve something like this:

Parameter a;
a.SetValue();
a.GetValue();     // compiles and run

// Parameter a1;
// a1.GetValue(); // does not compile

maybe using also a static_assert to display the error.

Thank you very much in advance for the help.

Aucun commentaire:

Enregistrer un commentaire