diff --git a/include/cantera/base/AnyMap.inl.h b/include/cantera/base/AnyMap.inl.h index b87ff3c55..907133483 100644 --- a/include/cantera/base/AnyMap.inl.h +++ b/include/cantera/base/AnyMap.inl.h @@ -16,6 +16,10 @@ namespace Cantera template 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(as()); + } return boost::any_cast(*m_value); } catch (boost::bad_any_cast&) { if (m_value->type() == typeid(void)) { @@ -32,6 +36,10 @@ const T &AnyValue::as() const { template 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(as()); + } return boost::any_cast(*m_value); } catch (boost::bad_any_cast&) { if (m_value->type() == typeid(void)) { @@ -107,13 +115,7 @@ std::map AnyValue::asMap() const { std::map dest; for (const auto& item : as().m_data) { - try { - dest[item.first] = boost::any_cast(*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(); } return dest; } diff --git a/src/base/AnyMap.cpp b/src/base/AnyMap.cpp index 1037d1c82..0c1325979 100644 --- a/src/base/AnyMap.cpp +++ b/src/base/AnyMap.cpp @@ -228,6 +228,7 @@ namespace Cantera std::map AnyValue::s_typenames = { {typeid(double).name(), "double"}, + {typeid(long int).name(), "long int"}, {typeid(std::string).name(), "string"}, {typeid(std::vector).name(), "vector"}, {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(as()); - } return as(); } const double& AnyValue::asDouble() const { - if (m_value->type() == typeid(long int)) { - *m_value = static_cast(as()); - } return as(); } diff --git a/test/general/test_containers.cpp b/test/general/test_containers.cpp index 23248ea13..9b25fc8b9 100644 --- a/test/general/test_containers.cpp +++ b/test/general/test_containers.cpp @@ -62,6 +62,13 @@ TEST(AnyMap, map_conversion) { EXPECT_THROW(m["foo"]["a"].asString(), CanteraError); EXPECT_THROW(m["foo"]["b"].asVector(), CanteraError); + + m["qux"]["c"] = 3; + m["qux"]["d"] = 3.14; + auto y = m["qux"].asMap(); + EXPECT_DOUBLE_EQ(y["c"], 3.0); + EXPECT_DOUBLE_EQ(y["d"], 3.14); + EXPECT_THROW(m["qux"].asMap(), CanteraError); } TEST(AnyMap, nested)