From 0712b481e90719c5c052cb3cb4b1ca45bf04abb1 Mon Sep 17 00:00:00 2001 From: Benjamin Nauck Date: Sun, 19 Jan 2025 01:46:46 +0100 Subject: [PATCH] App: Add Document::addObject(...) to simplify code --- src/App/Document.cpp | 16 ++++------------ src/App/Document.h | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/App/Document.cpp b/src/App/Document.cpp index 5a074d2a44..9b583183c0 100644 --- a/src/App/Document.cpp +++ b/src/App/Document.cpp @@ -3544,7 +3544,7 @@ DocumentObject* Document::addObject(const char* sType, const char* viewType, bool isPartial) { - Base::Type type = + const Base::Type type = Base::Type::getTypeIfDerivedFrom(sType, App::DocumentObject::getClassTypeId(), true); if (type.isBad()) { std::stringstream str; @@ -3557,8 +3557,7 @@ DocumentObject* Document::addObject(const char* sType, return nullptr; } - App::DocumentObject* pcObject = static_cast(typeInstance); - + auto* pcObject = static_cast(typeInstance); pcObject->setDocument(this); // do no transactions if we do a rollback! @@ -3571,15 +3570,8 @@ DocumentObject* Document::addObject(const char* sType, } // get Unique name - string ObjectName; - - if (pObjectName && pObjectName[0] != '\0') { - ObjectName = getUniqueObjectName(pObjectName); - } - else { - ObjectName = getUniqueObjectName(sType); - } - + const bool hasName = pObjectName && pObjectName[0] != '\0'; + const string ObjectName = getUniqueObjectName(hasName ? pObjectName : type.getName()); d->activeObject = pcObject; diff --git a/src/App/Document.h b/src/App/Document.h index b13b206bd0..cdabf8efce 100644 --- a/src/App/Document.h +++ b/src/App/Document.h @@ -268,6 +268,21 @@ public: bool isNew = true, const char* viewType = nullptr, bool isPartial = false); + //@{ + /** Add a feature of T type with sName (ASCII) to this document and set it active. + * Unicode names are set through the Label property. + * @param pObjectName if nonNULL use that name otherwise generate a new unique name based on the + * \a sType + * @param isNew if false don't call the \c DocumentObject::setupObject() callback (default + * is true) + * @param viewType override object's view provider name + * @param isPartial indicate if this object is meant to be partially loaded + */ + template + T* addObject(const char* pObjectName = nullptr, + bool isNew = true, + const char* viewType = nullptr, + bool isPartial = false); /** Add an array of features of the given types and names. * Unicode names are set through the Label property. * @param sType The type of created object @@ -662,6 +677,12 @@ inline int Document::countObjectsOfType() const return this->countObjectsOfType(T::getClassTypeId()); } +template +T* Document::addObject(const char* pObjectName, bool isNew, const char* viewType, bool isPartial) +{ + static_assert(std::is_base_of::value, "T must be derived from DocumentObject"); + return static_cast(addObject(T::getClassName(), pObjectName, isNew, viewType, isPartial)); +} } // namespace App