Skip to content

Commit b3949bc

Browse files
committed
Fix bug related to std::get<std::string>(pubKey) and std::bad_variant_access
1 parent 5b3c141 commit b3949bc

1 file changed

Lines changed: 26 additions & 4 deletions

File tree

Examples/Detectors/MuonSpectrometerMockupDetector/src/GeoMuonMockupExperiment.cpp

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,12 @@
1212
#include "Acts/Utilities/Helpers.hpp"
1313
#include "Acts/Utilities/MathHelpers.hpp"
1414

15+
#include <any>
1516
#include <format>
1617
#include <iostream>
17-
#include <any>
18+
#include <string>
19+
#include <string_view>
20+
#include <typeinfo>
1821

1922
#include <GeoModelWrite/WriteGeoModel.h>
2023

@@ -36,6 +39,25 @@ constexpr double rot90deg = 90. * GeoModelKernelUnits::deg;
3639

3740
namespace ActsExamples {
3841

42+
namespace {
43+
std::string pubKeyToString(const std::any& pubKey) {
44+
if (const auto* s = std::any_cast<std::string>(&pubKey); s != nullptr) {
45+
return *s;
46+
}
47+
if (const auto* s = std::any_cast<const char*>(&pubKey); s != nullptr &&
48+
*s != nullptr) {
49+
return std::string{*s};
50+
}
51+
if (const auto* s = std::any_cast<std::string_view>(&pubKey); s != nullptr) {
52+
return std::string{*s};
53+
}
54+
55+
throw std::domain_error(std::format(
56+
"GeoMuonMockupExperiment() - Published key is not a supported type; got '{}'",
57+
pubKey.type().name()));
58+
}
59+
} // namespace
60+
3961
std::string to_string(GeoMuonMockupExperiment::MuonLayer layer) {
4062
switch (layer) {
4163
using enum GeoMuonMockupExperiment::MuonLayer;
@@ -169,16 +191,16 @@ ActsPlugins::GeoModelTree GeoMuonMockupExperiment::constructMS() {
169191
VolumeMap_t publishedVol{};
170192
for (const auto& [fpV, pubKey] : m_publisher->getPublishedFPV()) {
171193
try {
172-
const auto key = std::any_cast<std::string>(pubKey);
194+
const auto key = pubKeyToString(pubKey);
173195
if (!publishedVol
174196
.insert(std::make_pair(key, static_cast<GeoFullPhysVol*>(fpV)))
175197
.second) {
176198
throw std::invalid_argument("GeoMuonMockupExperiment() - Key " + key +
177199
" is no longer unique");
178200
}
179-
} catch (const std::bad_any_cast& e) {
201+
} catch (const std::exception& e) {
180202
throw std::domain_error(
181-
"GeoMuonMockupExperiment() - Failed to cast the key to string " +
203+
"GeoMuonMockupExperiment() - Failed to convert published key to string: " +
182204
std::string{e.what()});
183205
}
184206
}

0 commit comments

Comments
 (0)