Allow conversion from long int to double in AnyValue.asMap

This commit is contained in:
Ray Speth 2018-12-05 16:22:44 -05:00
parent de80f06887
commit 0220e11ef9
3 changed files with 17 additions and 13 deletions

View file

@ -16,6 +16,10 @@ namespace Cantera
template<class T>
const T &AnyValue::as() const {
try {
if (typeid(T) == typeid(double) && m_value->type() == typeid(long int)) {
// Implicit conversion of long int to double
*m_value = static_cast<double>(as<long int>());
}
return boost::any_cast<const T&>(*m_value);
} catch (boost::bad_any_cast&) {
if (m_value->type() == typeid(void)) {
@ -32,6 +36,10 @@ const T &AnyValue::as() const {
template<class T>
T &AnyValue::as() {
try {
if (typeid(T) == typeid(double) && m_value->type() == typeid(long int)) {
// Implicit conversion of long int to double
*m_value = static_cast<double>(as<long int>());
}
return boost::any_cast<T&>(*m_value);
} catch (boost::bad_any_cast&) {
if (m_value->type() == typeid(void)) {
@ -107,13 +115,7 @@ std::map<std::string, T> AnyValue::asMap() const
{
std::map<std::string, T> dest;
for (const auto& item : as<AnyMap>().m_data) {
try {
dest[item.first] = boost::any_cast<T>(*item.second.m_value);
} catch (boost::bad_any_cast&) {
throw CanteraError("AnyValue::asMap",
"Value of key '{}' is not a '{}'",
item.first, demangle(typeid(T)));
}
dest[item.first] = item.second.as<T>();
}
return dest;
}

View file

@ -228,6 +228,7 @@ namespace Cantera
std::map<std::string, std::string> AnyValue::s_typenames = {
{typeid(double).name(), "double"},
{typeid(long int).name(), "long int"},
{typeid(std::string).name(), "string"},
{typeid(std::vector<double>).name(), "vector<double>"},
{typeid(AnyMap).name(), "AnyMap"},
@ -305,16 +306,10 @@ AnyValue &AnyValue::operator=(double value) {
}
double& AnyValue::asDouble() {
if (m_value->type() == typeid(long int)) {
*m_value = static_cast<double>(as<long int>());
}
return as<double>();
}
const double& AnyValue::asDouble() const {
if (m_value->type() == typeid(long int)) {
*m_value = static_cast<double>(as<long int>());
}
return as<double>();
}

View file

@ -62,6 +62,13 @@ TEST(AnyMap, map_conversion) {
EXPECT_THROW(m["foo"]["a"].asString(), CanteraError);
EXPECT_THROW(m["foo"]["b"].asVector<double>(), CanteraError);
m["qux"]["c"] = 3;
m["qux"]["d"] = 3.14;
auto y = m["qux"].asMap<double>();
EXPECT_DOUBLE_EQ(y["c"], 3.0);
EXPECT_DOUBLE_EQ(y["d"], 3.14);
EXPECT_THROW(m["qux"].asMap<long int>(), CanteraError);
}
TEST(AnyMap, nested)