Skip to content

Commit

Permalink
fix wrong enum conversion in variant function 'convert(bool* ok'
Browse files Browse the repository at this point in the history
When the conversion function was invoked and
the variant type was already an enum, the conversion failed.

This commit will fix it. Added missing test case for this behaviour.

Fixes #53
  • Loading branch information
acki-m committed May 7, 2017
1 parent 034ebcc commit 0e48f0b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 6 deletions.
25 changes: 19 additions & 6 deletions src/rttr/detail/variant/variant_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,26 @@ RTTR_INLINE detail::enable_if_t<!std::is_arithmetic<T>::value && !std::is_enum<T
template<typename T>
RTTR_INLINE detail::enable_if_t<std::is_enum<T>::value, T> variant::convert_impl(bool* ok) const
{
variant var = type::get<T>();
auto wrapper = std::ref(var);
const bool could_convert = convert<std::reference_wrapper<variant>>(wrapper);
if (ok)
*ok = could_convert;
const auto target_type = type::get<T>();
if (get_type() == target_type)
{
T result;
const auto could_convert = convert<T>(result);
if (ok)
*ok = could_convert;

return result;
}
else
{
variant var = type::get<T>();
auto wrapper = std::ref(var);
const auto could_convert = convert<std::reference_wrapper<variant>>(wrapper);
if (ok)
*ok = could_convert;

return var.get_value<T>();
return var.get_value<T>();
}
}

/////////////////////////////////////////////////////////////////////////////////////////
Expand Down
26 changes: 26 additions & 0 deletions src/unit_tests/variant/variant_conv_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,24 @@ struct other_derived : virtual base
RTTR_ENABLE(base)
};

enum class test_enum
{
first = 1,
second = 2
};

} // end anonymous namespace

RTTR_REGISTRATION
{
type::register_converter_func(convert_to_string);
type::register_converter_func(convert_to_vector);

registration::enumeration<test_enum>("test_enum")
(
value("first", test_enum::first),
value("second", test_enum::second)
);
}

/////////////////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -671,3 +683,17 @@ TEST_CASE("variant test - convert from wrapped value", "[variant]")
}

/////////////////////////////////////////////////////////////////////////////////////////

TEST_CASE("variant test - convert from enum", "[variant]")
{
auto ok = false;
rttr::variant var = type::get<test_enum>().get_enumeration().name_to_value("second");
test_enum converted = var.convert<test_enum>(&ok);

CHECK(ok == true);
CHECK(converted != test_enum::first);
CHECK(converted == test_enum::second);
CHECK(static_cast<int>(converted) == 2);
}

/////////////////////////////////////////////////////////////////////////////////////////

0 comments on commit 0e48f0b

Please sign in to comment.