From c28d3777bf5ee435e313e700bde2c0c84562b369 Mon Sep 17 00:00:00 2001 From: ljfa-ag Date: Sat, 18 Jul 2015 21:50:41 +0200 Subject: Add value::as method for conversion Make conversion operators explicit --- include/value.h | 35 ++++++++++++++++++++++++++++------- test/nbttest.cpp | 5 ++++- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/include/value.h b/include/value.h index a03395c2d1..c82aeb9097 100644 --- a/include/value.h +++ b/include/value.h @@ -66,6 +66,15 @@ public: tag& get(); const tag& get() const; + /** + * @brief Returns the contained tag as an instance of T + * @throw std::bad_cast if the tag is not of type T + */ + template + T& as(); + template + const T& as() const; + //Assignment of primitives and string /** * @brief Assigns the given value to the tag if the type is compatible @@ -92,12 +101,12 @@ public: * @throw std::bad_cast if the tag type is not convertible to the desired * type via a widening conversion */ - operator int8_t() const; - operator int16_t() const; - operator int32_t() const; - operator int64_t() const; - operator float() const; - operator double() const; + explicit operator int8_t() const; + explicit operator int16_t() const; + explicit operator int32_t() const; + explicit operator int64_t() const; + explicit operator float() const; + explicit operator double() const; /** * @brief Returns the contained string if the type is tag_string @@ -105,7 +114,7 @@ public: * If the value is uninitialized, the behavior is undefined. * @throw std::bad_cast if the tag type is not tag_string */ - operator const std::string&() const; + explicit operator const std::string&() const; ///Returns true if the value is not uninitialized explicit operator bool() const; @@ -167,6 +176,18 @@ private: std::unique_ptr tag_; }; +template +T& value::as() +{ + return dynamic_cast(get()); +} + +template +const T& value::as() const +{ + return dynamic_cast(get()); +} + } #endif // TAG_REF_PROXY_H_INCLUDED diff --git a/test/nbttest.cpp b/test/nbttest.cpp index 89ecdf8f85..ac9e5d5a30 100644 --- a/test/nbttest.cpp +++ b/test/nbttest.cpp @@ -199,6 +199,9 @@ void test_value() valstr = "bar"; EXPECT_EXCEPTION(valstr = 5, std::bad_cast); ASSERT(std::string(valstr) == "bar"); + ASSERT(valstr.as() == "bar"); + ASSERT(&valstr.as() == &valstr.get()); + EXPECT_EXCEPTION(valstr.as(), std::bad_cast); val1 = int64_t(42); ASSERT(val2 != val1); @@ -227,7 +230,7 @@ void test_value() tag = 21; ASSERT(int32_t(val3) == 21); val1.set_ptr(std::move(val3.get_ptr())); - ASSERT(tag_int(val1) == 21); + ASSERT(val1.as() == 21); ASSERT(val1.get_type() == tag_type::Int); ASSERT(val2.get_type() == tag_type::Null); -- cgit 0.0.5-2-1-g0f52