// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 #include "opentelemetry/nostd/variant.h" #include #include namespace nostd = opentelemetry::nostd; class DestroyCounter { public: explicit DestroyCounter(int *count) : count_{count} {} ~DestroyCounter() { ++*count_; } private: int *count_; }; TEST(VariantSizeTest, GetVariantSize) { EXPECT_EQ(nostd::variant_size>::value, 0); EXPECT_EQ(nostd::variant_size>::value, 1); EXPECT_EQ((nostd::variant_size>::value), 2); } #if 0 // Disable this test for now. It does not compile with Visual Studio 2015. TEST(VariantAlternativeTest, GetVariantSize) { EXPECT_TRUE((std::is_same>, int>::value)); EXPECT_TRUE( (std::is_same>, double>::value)); EXPECT_TRUE((std::is_same>, const double>::value)); } #endif TEST(VariantTest, Get) { nostd::variant v, w; v = 12; EXPECT_EQ(nostd::get(v), 12); EXPECT_EQ(nostd::get<0>(v), 12); w = v; EXPECT_EQ(nostd::get(w), 12); EXPECT_EQ(*nostd::get_if(&v), 12); EXPECT_EQ(nostd::get_if(&v), nullptr); #if __EXCEPTIONS || (defined(OPENTELEMETRY_STL_VERSION) && (OPENTELEMETRY_STL_VERSION >= 2017)) EXPECT_THROW(nostd::get(w), nostd::bad_variant_access); #else EXPECT_DEATH({ nostd::get(w); }, ""); #endif } TEST(VariantTest, Comparison) { nostd::variant v, w; EXPECT_TRUE(v == w); EXPECT_FALSE(v != w); v = 3.0f; EXPECT_TRUE(v != w); EXPECT_FALSE(v == w); v = 2; w = 3; EXPECT_TRUE(v != w); EXPECT_FALSE(v == w); EXPECT_TRUE(v < w); EXPECT_FALSE(v > w); } TEST(VariantTest, Visit) { nostd::variant v; struct { int operator()(int) { return 0; } int operator()(float) { return 1; } } a; EXPECT_EQ(nostd::visit(a, v), 0); v = 2.0f; EXPECT_EQ(nostd::visit(a, v), 1); } TEST(VariantTest, Destructor) { nostd::variant v; int destroy_count = 0; v = DestroyCounter{&destroy_count}; destroy_count = 0; v = 1; EXPECT_EQ(destroy_count, 1); { nostd::variant w; w = DestroyCounter{&destroy_count}; destroy_count = 0; } EXPECT_EQ(destroy_count, 1); } TEST(VariantTest, Conversion) { nostd::variant x("abc"); x = "def"; EXPECT_EQ(nostd::get(x), "def"); nostd::variant y("abc"); EXPECT_TRUE(nostd::holds_alternative(y)); y = std::string{"xyz"}; EXPECT_TRUE(nostd::holds_alternative(y)); } TEST(VariantTest, Construction) { nostd::variant v{"abc"}; EXPECT_EQ(v.index(), 1); }