diff --git a/Core/include/Acts/Utilities/detail/ContextType.hpp b/Core/include/Acts/Utilities/detail/ContextType.hpp index 143e8b2d521..8ccadd77c4d 100644 --- a/Core/include/Acts/Utilities/detail/ContextType.hpp +++ b/Core/include/Acts/Utilities/detail/ContextType.hpp @@ -79,6 +79,28 @@ class ContextType { return std::any_cast&>(m_data); } + /// Retrieve a pointer to the contained type + /// + /// @note Returns `nullptr` if @p is not the contained type. + /// + /// @tparam T The type to attempt to retrieve the value as + /// @return Pointer to the contained value, may be null + template + std::decay_t* maybeGet() { + return std::any_cast>(&m_data); + } + + /// Retrieve a pointer to the contained type + /// + /// @note Returns `nullptr` if @p is not the contained type. + /// + /// @tparam T The type to attempt to retrieve the value as + /// @return Pointer to the contained value, may be null + template + const std::decay_t* maybeGet() const { + return std::any_cast>(&m_data); + } + /// Check if the contained type is initialized. /// @return Boolean indicating whether a type is present bool hasValue() const { return m_data.has_value(); } diff --git a/Tests/UnitTests/Core/Utilities/CMakeLists.txt b/Tests/UnitTests/Core/Utilities/CMakeLists.txt index cb5249b6be9..955b58b31c9 100644 --- a/Tests/UnitTests/Core/Utilities/CMakeLists.txt +++ b/Tests/UnitTests/Core/Utilities/CMakeLists.txt @@ -61,3 +61,4 @@ add_unittest(VectorHelpers VectorHelpersTests.cpp) add_unittest(TrackHelpers TrackHelpersTests.cpp) add_unittest(GraphViz GraphVizTests.cpp) +add_unittest(ContextType ContextTypeTests.cpp) diff --git a/Tests/UnitTests/Core/Utilities/ContextTypeTests.cpp b/Tests/UnitTests/Core/Utilities/ContextTypeTests.cpp new file mode 100644 index 00000000000..2bd67ee1e5f --- /dev/null +++ b/Tests/UnitTests/Core/Utilities/ContextTypeTests.cpp @@ -0,0 +1,38 @@ +// This file is part of the ACTS project. +// +// Copyright (C) 2016 CERN for the benefit of the ACTS project +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#include +#include + +#include "Acts/Utilities/detail/ContextType.hpp" + +using namespace Acts; + +BOOST_AUTO_TEST_SUITE(ContextTypeTests) + +BOOST_AUTO_TEST_CASE(PackUnpack) { + ContextType ctx; + + int v = 42; + ctx = v; + + BOOST_CHECK_EQUAL(ctx.get(), 42); + BOOST_CHECK_THROW(ctx.get(), std::bad_any_cast); +} + +BOOST_AUTO_TEST_CASE(MaybeUnpack) { + ContextType ctx; + + int v = 42; + ctx = v; + + BOOST_CHECK_EQUAL(*ctx.maybeGet(), 42); + BOOST_CHECK_EQUAL(ctx.maybeGet(), nullptr); +} + +BOOST_AUTO_TEST_SUITE_END()