Skip to content

Commit

Permalink
add which() method returning zero based index of stored T in Types...…
Browse files Browse the repository at this point in the history
… for boost::variant() compatibility
  • Loading branch information
artemp committed Mar 4, 2015
1 parent c117592 commit 3b02ca0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
13 changes: 12 additions & 1 deletion test/unit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,18 @@ TEST_CASE( "variant should correctly index types", "[variant]" ) {
REQUIRE(variant_type(float(0.0)).get_type_index() == 0);
}

// Test internal api
TEST_CASE( "variant::which() returns zero based index of stored type", "[variant]" ) {
typedef util::variant<bool,std::string,std::uint64_t,std::int64_t,double,float> variant_type;
// Index is in reverse order
REQUIRE(variant_type(true).which() == 0);
REQUIRE(variant_type(std::string("test")).which() == 1);
REQUIRE(variant_type(std::uint64_t(0)).which() == 2);
REQUIRE(variant_type(std::int64_t(0)).which() == 3);
REQUIRE(variant_type(double(0.0)).which() == 4);
REQUIRE(variant_type(float(0.0)).which() == 5);
}

TEST_CASE( "get with type not in variant type list should throw", "[variant]" ) {
typedef util::variant<int> variant_type;
variant_type var = 5;
Expand Down Expand Up @@ -294,7 +306,6 @@ TEST_CASE( "variant printer", "[visitor][unary visitor][printer]" ) {
REQUIRE(out.str() == "2.1,123,foo,456,foo");
}


int main (int argc, char* const argv[])
{
int result = Catch::Session().run(argc, argv);
Expand Down
5 changes: 5 additions & 0 deletions variant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,11 @@ class variant
return type_index;
}

VARIANT_INLINE int which() const noexcept
{
return static_cast<int>(sizeof...(Types) - type_index - 1);
}

// visitor
// unary
template <typename F, typename V>
Expand Down

0 comments on commit 3b02ca0

Please sign in to comment.