Improve dcast

* document `dcast`
* make `dcast` not only cast exact, but also upwards
* add `dcast` test
* rename `dcast` -> `dynamicCast`
This commit is contained in:
Johannes Lorenz
2019-04-27 00:29:49 +02:00
parent d06f5088a1
commit 0fd5693e12
5 changed files with 96 additions and 12 deletions

View File

@@ -92,18 +92,25 @@ public:
virtual void accept(ConstModelVisitor& v) const = 0;
public:
//! Return this class casted to Target, or nullptr if impossible
/**
@brief Return this class casted to Target
@test AutomatableModelTest.cpp
@param doThrow throw an assertion if the cast fails, instead of
returning a nullptr
@return the casted class if Target is the exact or a base class of
*this, nullptr otherwise
*/
template<class Target>
Target* dcast(bool doThrow = false)
Target* dynamicCast(bool doThrow = false)
{
DCastVisitor<Target> vis; accept(vis);
if(doThrow && !vis.result) Q_ASSERT(false);
return vis.result;
}
//! Return this class casted to const Target, or nullptr if impossible
//! const overload, see overloaded function
template<class Target>
const Target* dcast(bool doThrow = false) const
const Target* dynamicCast(bool doThrow = false) const
{
ConstDCastVisitor<Target> vis; accept(vis);
if(doThrow && !vis.result) Q_ASSERT(false);
@@ -312,6 +319,7 @@ protected:
private:
// dynamicCast implementation
template<class Target>
struct DCastVisitor : public ModelVisitor
{
@@ -319,6 +327,7 @@ private:
void visit(Target& tar) { result = &tar; }
};
// dynamicCast implementation
template<class Target>
struct ConstDCastVisitor : public ConstModelVisitor
{

View File

@@ -25,6 +25,7 @@
#ifndef MODELVISITOR_H
#define MODELVISITOR_H
class AutomatableModel;
class BoolModel;
class IntModel;
class FloatModel;
@@ -32,21 +33,28 @@ class ComboBoxModel;
class ModelVisitor
{
template<class ParentType = AutomatableModel, class ModelType>
void up(ModelType& m) { visit(static_cast<ParentType&>(m)); }
public:
virtual void visit(BoolModel& ) {}
virtual void visit(IntModel& ) {}
virtual void visit(FloatModel& ) {}
virtual void visit(ComboBoxModel& ) {}
virtual void visit(AutomatableModel& ) {}
virtual void visit(BoolModel& m);
virtual void visit(IntModel& );
virtual void visit(FloatModel& );
virtual void visit(ComboBoxModel& );
virtual ~ModelVisitor();
};
class ConstModelVisitor
{
template<class ParentType = AutomatableModel, class ModelType>
void up(const ModelType& m) {
visit(static_cast<const ParentType&>(m)); }
public:
virtual void visit(const BoolModel& ) {}
virtual void visit(const IntModel& ) {}
virtual void visit(const FloatModel& ) {}
virtual void visit(const ComboBoxModel& ) {}
virtual void visit(const AutomatableModel& ) {}
virtual void visit(const BoolModel& m);
virtual void visit(const IntModel& m);
virtual void visit(const FloatModel& m);
virtual void visit(const ComboBoxModel& m);
virtual ~ConstModelVisitor();
};