From 7626425b2c6299b38865aa10c8d912e946f5f88f Mon Sep 17 00:00:00 2001 From: ljfa-ag Date: Wed, 5 Aug 2015 17:06:40 +0200 Subject: Add tag::as method --- include/tag.h | 23 +++++++++++++++++++++++ include/value.h | 8 +++----- 2 files changed, 26 insertions(+), 5 deletions(-) (limited to 'include') diff --git a/include/tag.h b/include/tag.h index 58b99c082c..569da446d6 100644 --- a/include/tag.h +++ b/include/tag.h @@ -70,6 +70,15 @@ public: virtual std::unique_ptr move_clone() && = 0; std::unique_ptr clone() &&; + /** + * @brief Returns a reference to the 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; + /** * @brief Move-assigns the given tag if the class is the same * @throw std::bad_cast if @c rhs is not the same type as @c *this @@ -101,6 +110,20 @@ private: std::ostream& operator<<(std::ostream& os, tag_type tt); +template +T& tag::as() +{ + static_assert(std::is_base_of::value, "T must be a subclass of tag"); + return dynamic_cast(*this); +} + +template +const T& tag::as() const +{ + static_assert(std::is_base_of::value, "T must be a subclass of tag"); + return dynamic_cast(*this); +} + } #endif // TAG_H_INCLUDED diff --git a/include/value.h b/include/value.h index c017bcbd27..4865c8fd1c 100644 --- a/include/value.h +++ b/include/value.h @@ -93,7 +93,7 @@ public: const tag& get() const; /** - * @brief Returns the contained tag as an instance of T + * @brief Returns a reference to the contained tag as an instance of T * @throw std::bad_cast if the tag is not of type T */ template @@ -207,15 +207,13 @@ private: template T& value::as() { - static_assert(std::is_base_of::value, "T must be a subclass of tag"); - return dynamic_cast(get()); + return tag_->as(); } template const T& value::as() const { - static_assert(std::is_base_of::value, "T must be a subclass of tag"); - return dynamic_cast(get()); + return tag_->as();; } } -- cgit 0.0.5-2-1-g0f52