Skip to content

Commit 12c7093

Browse files
committed
Add tests for implicit conversion and exceptions for wrong types.
1 parent a123269 commit 12c7093

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

test/unit.cpp

+51
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,59 @@ TEST_CASE( "variant should correctly index types", "[variant]" ) {
208208
REQUIRE(variant_type(float(0.0)).get_type_index() == 0);
209209
}
210210

211+
TEST_CASE( "get with type not in variant type list should throw", "[variant]" ) {
212+
typedef util::variant<int> variant_type;
213+
variant_type var = 5;
214+
REQUIRE(var.get<int>() == 5);
215+
REQUIRE_THROWS(var.get<double>()); // XXX shouldn't this be a compile time error? See https://github.com/mapbox/variant/issues/24
216+
}
217+
218+
TEST_CASE( "get with wrong type (here: double) should throw", "[variant]" ) {
219+
typedef util::variant<int, double> variant_type;
220+
variant_type var = 5;
221+
REQUIRE(var.get<int>() == 5);
222+
REQUIRE_THROWS(var.get<double>());
223+
}
224+
225+
TEST_CASE( "get with wrong type (here: int) should throw", "[variant]" ) {
226+
typedef util::variant<int, double> variant_type;
227+
variant_type var = 5.0;
228+
REQUIRE(var.get<double>() == 5.0);
229+
REQUIRE_THROWS(var.get<int>());
230+
}
231+
232+
TEST_CASE( "implicit conversion", "[variant][implicit conversion]" ) {
233+
typedef util::variant<int> variant_type;
234+
variant_type var(5.0); // converted to int
235+
REQUIRE(var.get<int>() == 5);
236+
REQUIRE_THROWS(var.get<double>());
237+
var = 6.0; // works for operator=, too
238+
REQUIRE(var.get<int>() == 6);
239+
}
240+
241+
TEST_CASE( "implicit conversion to first type in variant type list", "[variant][implicit conversion]" ) {
242+
typedef util::variant<long, char> variant_type;
243+
variant_type var = 5.0; // converted to long
244+
REQUIRE(var.get<long>() == 5);
245+
REQUIRE_THROWS(var.get<char>());
246+
REQUIRE_THROWS(var.get<double>());
247+
}
248+
211249
struct dummy {};
212250

251+
TEST_CASE( "implicit conversion to first type it can convert to even if it doesn't fit", "[variant][implicit conversion]" ) {
252+
typedef util::variant<dummy, unsigned char, long> variant_type;
253+
variant_type var = 500.0; // converted to unsigned char, even if it doesn't fit
254+
REQUIRE(var.get<unsigned char>() == static_cast<unsigned char>(500.0));
255+
REQUIRE_THROWS(var.get<long>());
256+
var = 500; // int converted to unsigned char, even if it doesn't fit
257+
REQUIRE(var.get<unsigned char>() == static_cast<unsigned char>(500));
258+
REQUIRE_THROWS(var.get<long>());
259+
var = 500L; // explicit long is okay
260+
REQUIRE(var.get<long>() == 500L);
261+
REQUIRE_THROWS(var.get<char>());
262+
}
263+
213264
TEST_CASE( "variant value traits", "[variant::detail]" ) {
214265
// Users should not create variants with duplicated types
215266
// however our type indexing should still work

0 commit comments

Comments
 (0)