App: Add Document::addObject<T>(...) to simplify code

This commit is contained in:
Benjamin Nauck
2025-01-19 01:46:46 +01:00
parent ddb0113ded
commit 0712b481e9
2 changed files with 25 additions and 12 deletions

View File

@@ -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<App::DocumentObject*>(typeInstance);
auto* pcObject = static_cast<App::DocumentObject*>(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;

View File

@@ -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<typename T>
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<typename T>
T* Document::addObject(const char* pObjectName, bool isNew, const char* viewType, bool isPartial)
{
static_assert(std::is_base_of<DocumentObject, T>::value, "T must be derived from DocumentObject");
return static_cast<T*>(addObject(T::getClassName(), pObjectName, isNew, viewType, isPartial));
}
} // namespace App