#include <stdexcept>
#include <iostream>
struct vapour_pressure
{
enum status_t { nonsense, unknown, known, saturated } ;
vapour_pressure() = default ;
vapour_pressure( double v) { *this = v ; }
vapour_pressure& operator= ( double v )
{
value = v ;
if( value < 0 ) status = nonsense ;
// else if ...
else status = known ;
return *this ;
}
operator double() const
{
if( status == nonsense ) throw std::domain_error("nonsense") ;
if( status == unknown ) throw std::domain_error("unknown") ;
return value ;
}
bool valid() const { return status == known || status == saturated ; }
operator bool () const { return valid() && value ; }
bool operator! () const { return !bool(*this) ; }
// etc.
private:
double value ;
status_t status = unknown ;
// ...
friend std::ostream& operator<< ( std::ostream& stm, const vapour_pressure& vp )
{
if( vp.status == vapour_pressure::unknown ) return stm << "unknown" ;
else if( vp.status == vapour_pressure::nonsense ) return stm << "nonsense" ;
else if( vp.status == vapour_pressure::saturated ) return stm << "saturated" ;
else return stm << vp.value ;
}
};
int main()
{
vapour_pressure vp ;
std::cout << "vapour pressure is: " << vp << '\n' ;
if(vp) { double val = vp ; /* ... */ }
vp = 23.4 ;
std::cout << "vapour pressure is: " << vp << '\n' ;
if( vp.valid() ) { double psi = double(vp) * 14.5038 ; /* ... */ }
vp = -3 ;
std::cout << "vapour pressure is: " << vp << '\n' ;
}