Skip to content

Commit

Permalink
feat: Add optional context type getter (acts-project#3853)
Browse files Browse the repository at this point in the history
Also adds a unit test.
  • Loading branch information
paulgessinger authored and Rosie-Hasan committed Nov 13, 2024
1 parent f335b09 commit f796676
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Core/include/Acts/Utilities/detail/ContextType.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,28 @@ class ContextType {
return std::any_cast<const std::decay_t<T>&>(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 <typename T>
std::decay_t<T>* maybeGet() {
return std::any_cast<std::decay_t<T>>(&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 <typename T>
const std::decay_t<T>* maybeGet() const {
return std::any_cast<const std::decay_t<T>>(&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(); }
Expand Down
1 change: 1 addition & 0 deletions Tests/UnitTests/Core/Utilities/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,4 @@ add_unittest(VectorHelpers VectorHelpersTests.cpp)

add_unittest(TrackHelpers TrackHelpersTests.cpp)
add_unittest(GraphViz GraphVizTests.cpp)
add_unittest(ContextType ContextTypeTests.cpp)
38 changes: 38 additions & 0 deletions Tests/UnitTests/Core/Utilities/ContextTypeTests.cpp
Original file line number Diff line number Diff line change
@@ -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 <boost/test/tools/old/interface.hpp>
#include <boost/test/unit_test.hpp>

#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<int>(), 42);
BOOST_CHECK_THROW(ctx.get<double>(), std::bad_any_cast);
}

BOOST_AUTO_TEST_CASE(MaybeUnpack) {
ContextType ctx;

int v = 42;
ctx = v;

BOOST_CHECK_EQUAL(*ctx.maybeGet<int>(), 42);
BOOST_CHECK_EQUAL(ctx.maybeGet<double>(), nullptr);
}

BOOST_AUTO_TEST_SUITE_END()

0 comments on commit f796676

Please sign in to comment.