CETL 0.0.0
 
Loading...
Searching...
No Matches
Example 10: Using CETL's unbounded_variant

Full example for cetl::unbounded_variant

#include <gmock/gmock.h>
namespace cetl
{
template <>
constexpr type_id type_id_getter<bool>() noexcept
{
return {1};
}
template <>
constexpr type_id type_id_getter<int>() noexcept
{
return {2};
}
template <>
constexpr type_id type_id_getter<float>() noexcept
{
return {3};
}
template <>
constexpr type_id type_id_getter<double>() noexcept
{
return {4};
}
}// namespace cetl
TEST(example_10_unbounded_variant, basic_usage)
{
using ub_var = cetl::unbounded_variant<std::max(sizeof(int), sizeof(double))>;
ub_var a = 1;
EXPECT_THAT(cetl::get<int>(a), 1);
a = 3.14;
EXPECT_THAT(cetl::get<double>(a), 3.14);
a = true;
EXPECT_TRUE(cetl::get<bool>(a));
// bad any cast
//
a = 1;
#ifdefined(__cpp_exceptions)
// Workaround for GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425
// Should be used in the tests where exceptions are expected (see `EXPECT_THROW`).
const auto sink = [](auto&&) {};
#else
EXPECT_THAT(cetl::get_if<float>(&a), testing::IsNull());
#endif
a = 2;
EXPECT_TRUE(a.has_value());
// reset
//
a.reset();
EXPECT_FALSE(a.has_value());
// pointer to contained data
//
a = 3;
EXPECT_THAT(*cetl::get_if<int>(&a), 3);
}
Defines a type of object to be thrown by the get on failure.
Definition unbounded_variant.hpp:30
The class unbounded_variant describes a type-safe container for single values of unbounded_variant co...
Definition unbounded_variant.hpp:1032
T max(T... args)
This namespace contains types specific to CETL and nested namespaces that contain types adhering to t...
Definition _helper_enable_copy_move.hpp:10
constexpr type_id type_id_getter() noexcept
The type ID getter for the given type.
Definition rtti.hpp:85
std::add_pointer_t< ValueType > get_if(UnboundedVariant *operand) noexcept
Performs type-safe access to the contained object.
Definition unbounded_variant.hpp:1720
CETL_NODISCARD ValueType get(const UnboundedVariant &operand)
Performs type-safe access to the contained object.
Definition unbounded_variant.hpp:1625
std::array< std::uint8_t, type_id_size > type_id
A 16-byte UUID (GUID) that uniquely identifies a type.
Definition rtti.hpp:32
Includes cetl::unbounded_variant type and non-member functions.