Add const accessors to antlrcpp::Any C++ class

To make it easier to work with the const antlrcpp::Any arguments to
the AbstractParseTreeVisitor class aggregateResult and
shouldVisitNextChild functions, add a public const overload for the
antlrcpp::Any::as member function to return a const StorageType&, and
add a public const overloaded conversion operator returning a const
instance of the type contained within the Any.

Add the private antlrcpp::Any::getDerived function to avoid
duplicating the dynamic_cast of the internal pointer, and call it from
the overloaded Any::as functions and also the Any::is function.
This commit is contained in:
Steve Vinoski 2018-11-12 15:03:04 -05:00
parent dc3b43376c
commit 875aa034d2
2 changed files with 26 additions and 8 deletions

View File

@ -203,4 +203,5 @@ YYYY/MM/DD, github id, Full name, email
2018/07/27, Maksim Novikov, mnovikov.work@gmail.com
2018/07/31 Lucas Henrqiue, lucashenrique580@gmail.com
2018/08/03, ENDOH takanao, djmchl@gmail.com
2018/10/29, chrisaycock, Christopher Aycock, chris[at]chrisaycock[dot]com
2018/10/29, chrisaycock, Christopher Aycock, chris[at]chrisaycock[dot]com
2018/11/12, vinoski, Steve Vinoski, vinoski@ieee.org

View File

@ -46,21 +46,21 @@ struct ANTLR4CPP_PUBLIC Any
template<class U>
bool is() const {
typedef StorageType<U> T;
auto derived = dynamic_cast<Derived<T> *>(_ptr);
auto derived = getDerived<U>();
return derived != nullptr;
}
template<class U>
StorageType<U>& as() {
typedef StorageType<U> T;
auto derived = getDerived<U>();
auto derived = dynamic_cast<Derived<T>*>(_ptr);
return derived->value;
}
if (!derived)
throw std::bad_cast();
template<class U>
const StorageType<U>& as() const {
auto derived = getDerived<U>();
return derived->value;
}
@ -70,6 +70,11 @@ struct ANTLR4CPP_PUBLIC Any
return as<StorageType<U>>();
}
template<class U>
operator const U() const {
return as<const StorageType<U>>();
}
Any& operator = (const Any& a) {
if (_ptr == a._ptr)
return *this;
@ -137,6 +142,18 @@ private:
return nullptr;
}
template<class U>
Derived<StorageType<U>>* getDerived() const {
typedef StorageType<U> T;
auto derived = dynamic_cast<Derived<T>*>(_ptr);
if (!derived)
throw std::bad_cast();
return derived;
}
Base *_ptr;
};