Use a universal reference to implement dereferenceMaybe()

charconv
Martchus 3 years ago
parent 0733f0705d
commit c7c5352325
  1. 16
      misc/traits.h
  2. 5
      tests/traitstests.cpp

@ -159,25 +159,13 @@ CPP_UTILITIES_TRAITS_DEFINE_TYPE_CHECK(IsIteratable,
void(*begin(std::declval<T &>())));
/// \brief Dereferences the specified \a value if possible; otherwise just returns \a value itself.
template <typename T, EnableIf<IsDereferencable<T>> * = nullptr> constexpr auto &dereferenceMaybe(T &value)
template <typename T, EnableIf<IsDereferencable<T>> * = nullptr> constexpr auto &dereferenceMaybe(T &&value)
{
return *value;
}
/// \brief Dereferences the specified \a value if possible; otherwise just returns \a value itself.
template <typename T, DisableIf<IsDereferencable<T>> * = nullptr> constexpr auto &dereferenceMaybe(T &value)
{
return value;
}
/// \brief Dereferences the specified \a value if possible; otherwise just returns \a value itself.
template <typename T, EnableIf<IsDereferencable<T>> * = nullptr> constexpr const auto &dereferenceMaybe(const T &value)
{
return *value;
}
/// \brief Dereferences the specified \a value if possible; otherwise just returns \a value itself.
template <typename T, DisableIf<IsDereferencable<T>> * = nullptr> constexpr const auto &dereferenceMaybe(const T &value)
template <typename T, DisableIf<IsDereferencable<T>> * = nullptr> constexpr auto &dereferenceMaybe(T &&value)
{
return value;
}

@ -133,8 +133,9 @@ CPPUNIT_TEST_SUITE_REGISTRATION(TraitsTest);
*/
void TraitsTest::testDereferenceMaybe()
{
const auto someString = "foo"s;
const auto someSmartPointer = make_unique<string>("foo");
auto someString = "foo"s;
auto someSmartPointer = make_unique<string>("foo");
CPPUNIT_ASSERT_EQUAL("foo"s, dereferenceMaybe(someString));
CPPUNIT_ASSERT_EQUAL("foo"s, dereferenceMaybe(someSmartPointer));
CPPUNIT_ASSERT_EQUAL("foo"s, dereferenceMaybe(make_unique<string>("foo")));
}

Loading…
Cancel
Save