ENH: Allow explicit construct Switch from float/double

- can be useful when a scalarField has been used to store booleans and
  we need to recover a bool directly and deal with potential rounding
  issues.

ENH: support "any" as a Switch counterpart to "none"
This commit is contained in:
Mark Olesen
2019-11-19 08:26:43 +01:00
committed by Andrew Heather
parent cf917b4103
commit 0597172940
2 changed files with 27 additions and 5 deletions

View File

@ -27,6 +27,7 @@ License
\*---------------------------------------------------------------------------*/
#include "Switch.H"
#include "scalar.H"
#include "error.H"
#include "dictionary.H"
#include "IOstreams.H"
@ -48,7 +49,7 @@ static const char* names[9] =
"false", "true",
"no", "yes",
"off", "on",
"none", "(unused)",
"none", "any",
"invalid"
};
@ -58,7 +59,7 @@ static const char* names[9] =
const char* Foam::Switch::name(const bool b) noexcept
{
return names[(b ? 0 : 1)];
return names[(b ? 1 : 0)];
}
@ -87,10 +88,11 @@ Foam::Switch::switchType Foam::Switch::parse
if (str == names[switchType::ON]) return switchType::ON;
break;
}
case 3: // (off|yes)
case 3: // (off|yes|any)
{
if (str == names[switchType::OFF]) return switchType::OFF;
if (str == names[switchType::YES]) return switchType::YES;
if (str == names[switchType::ANY]) return switchType::ANY;
break;
}
case 4: // (none|true)
@ -130,6 +132,18 @@ Foam::Switch Foam::Switch::getOrAddToDict
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::Switch::Switch(const float val, const float tol)
:
switch_((mag(val) > tol) ? switchType::TRUE : switchType::FALSE)
{}
Foam::Switch::Switch(const double val, const double tol)
:
switch_((mag(val) > tol) ? switchType::TRUE : switchType::FALSE)
{}
Foam::Switch::Switch
(
const word& key,

View File

@ -82,7 +82,7 @@ public:
FALSE = 0 /*!< "false" */, TRUE = 1 /*!< "true" */,
NO = 2 /*!< "no" */, YES = 3 /*!< "yes" */,
OFF = 4 /*!< "off" */, ON = 5 /*!< "on" */,
NONE = 6 /*!< "none" */,
NONE = 6 /*!< "none" */, ANY = 7 /*!< "any" */,
INVALID = 8 /*!< "invalid" */
};
@ -123,12 +123,20 @@ public:
switch_(b ? switchType::TRUE : switchType::FALSE)
{}
//- Construct from integer values (treats integer as bool value)
//- Construct from int (treat integer as bool value)
constexpr Switch(const int i) noexcept
:
switch_(i ? switchType::TRUE : switchType::FALSE)
{}
//- Construct from float with rounding to zero given by
//- the tolerance (default: 0.5)
explicit Switch(const float val, const float tol=0.5);
//- Construct from double with rounding to zero given by
//- the tolerance (default: 0.5)
explicit Switch(const double val, const double tol=0.5);
//- Construct from string - catches bad input.
explicit Switch(const std::string& str)
: