diff --git a/dune/xt/common/fixed_map.hh b/dune/xt/common/fixed_map.hh index 8d6f4d524e7d28a72f275c0f49d3970d123fe16c..cbbef9c38ae343a39f0b788661a1a3ff6b34a33d 100644 --- a/dune/xt/common/fixed_map.hh +++ b/dune/xt/common/fixed_map.hh @@ -129,6 +129,30 @@ private: typedef FixedMap<key_imp, T, nin> ThisType; + template <class K> // for sfinae to work this needs to be a template although the type is already fixed + typename std::enable_if<std::is_convertible<K, std::string>::value, std::string>::type + range_error_message(K key) const + { + std::stringstream ss; + ss << "missing key '" << key << "' in FixedMap!"; + return ss.str(); + } + + template <class K> + typename std::enable_if<std::is_convertible<K, int>::value, std::string>::type range_error_message(K key) const + { + std::stringstream ss; + ss << "missing key (converted to int)'" << int(key) << "' in FixedMap!"; + return ss.str(); + } + + template <class K> + typename std::enable_if<!(std::is_convertible<K, int>::value || std::is_convertible<K, std::string>::value), + std::string>::type range_error_message(K /*key*/) const + { + return "missing key is not printable"; + } + public: typedef key_imp key_type; typedef T mapped_type; @@ -166,7 +190,7 @@ public: { const auto it = get_idx(key); if (it == N) - DUNE_THROW(RangeError, "missing key '" << key << "' in FixedMap!"); + DUNE_THROW(RangeError, range_error_message(key)); return map_[it].second; } @@ -174,7 +198,7 @@ public: { const auto it = get_idx(key); if (it == N) - DUNE_THROW(RangeError, "missing key '" << key << "' in FixedMap!"); + DUNE_THROW(RangeError, range_error_message(key)); return map_[it].second; } diff --git a/dune/xt/common/test/fixed_map.cc b/dune/xt/common/test/fixed_map.cc index 2ad6de0cb9a43f2b9c497a8ec2ba865b9347b13c..afc3312c255513c9f03aeb25defaf9c346c45668 100644 --- a/dune/xt/common/test/fixed_map.cc +++ b/dune/xt/common/test/fixed_map.cc @@ -21,6 +21,14 @@ using namespace Dune::XT::Common; +enum class TestEnum +{ + one, + two, + three +}; + + GTEST_TEST(FixedMapTest, All) { const std::initializer_list<std::pair<std::string, int>> values{{"0", 0}, {"1", 1}, {"2", 2}}; @@ -55,4 +63,7 @@ GTEST_TEST(FixedMapTest, All) EXPECT_EQ(std::make_pair(std::string("0"), 0), *too_big.begin()); // EXPECT_DEATH(*too_big.end(), ".*"); + + FixedMap<TestEnum, std::string, 1> enum_names = {{TestEnum::one, "one"}}; + EXPECT_EQ(std::string("one"), enum_names[TestEnum::one]); }