From 82f8e3d62c7764eca78816bb980391ab52ac836c Mon Sep 17 00:00:00 2001 From: Heiko Strathmann Date: Mon, 5 Mar 2018 16:00:01 +0000 Subject: [PATCH] add const version of as --- src/shogun/base/SGObject.h | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/src/shogun/base/SGObject.h b/src/shogun/base/SGObject.h index 02d0c8dc7fc..92bb6227889 100644 --- a/src/shogun/base/SGObject.h +++ b/src/shogun/base/SGObject.h @@ -492,11 +492,11 @@ class CSGObject */ std::vector parameter_names() const; - /** - * Utility method to specialize the feature to the required type. + /** Specializes a provided object to the specified type. + * Throws exception if the object cannot be specialized. * - * @param sgo CSGObject base type - * @return The requested type if casting was successful. + * @param sgo object of CSGObject base type + * @return The requested type */ template static T* as(CSGObject* sgo) { @@ -504,24 +504,39 @@ class CSGObject return sgo->as(); } - /** - * Utility method to specialize the feature to the required type. + /** Specializes the object to the specified type. + * Throws exception if the object cannot be specialized. * - * @param sgo CSGObject base type - * @return The requested type if casting was successful, or throws exception. + * @return The requested type */ template T* as() { - T* c = dynamic_cast(this); + auto c = dynamic_cast(this); if (c) return c; - SG_SERROR("The object (%s) cannot be casted to the requested type %s!\n", + SG_SERROR("Object of type %s cannot be converted to type %s.\n", demangled_type>().c_str(), demangled_type().c_str()); return nullptr; } + /** Specializes the object to the specified type. + * Throws exception if the object cannot be specialized. + * + * @return The requested type + */ + template const T* as() const + { + auto c = dynamic_cast(this); + if (c) + return c; + + SG_SERROR("Object of type %s cannot be converted to type %s.\n", + demangled_type>().c_str(), + demangled_type().c_str()); + return nullptr; + } #ifndef SWIG /** * Get parameters observable