Skip to content

Commit

Permalink
libcore|Variable: Added an automatic cast to non-const Record
Browse files Browse the repository at this point in the history
  • Loading branch information
skyjake committed Aug 16, 2014
1 parent 554da99 commit a4f87b9
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 15 deletions.
32 changes: 18 additions & 14 deletions doomsday/libcore/include/de/data/variable.h
Expand Up @@ -176,6 +176,20 @@ class DENG2_PUBLIC Variable : public ISerializable
return *v;
}

/**
* Returns the value of the variable.
*/
template <typename Type>
Type const &value() const {
Type const *v = dynamic_cast<Type const *>(valuePtr());
if(!v) {
/// @throw TypeError Casting to Type failed.
throw TypeError("Variable::value",
QString("Illegal type conversion to ") + typeid(Type).name());
}
return *v;
}

/**
* Returns the Record that the variable references. If the variable does
* not have a RecordValue, an exception is thrown.
Expand All @@ -184,27 +198,17 @@ class DENG2_PUBLIC Variable : public ISerializable
*/
Record const &valueAsRecord() const;

Record &valueAsRecord();

operator Record & ();

operator Record const & () const;

// Automatic conversion to native primitive types.
operator String () const;
operator QString () const;
operator ddouble () const;

/**
* Returns the value of the variable.
*/
template <typename Type>
Type const &value() const {
Type const *v = dynamic_cast<Type const *>(valuePtr());
if(!v) {
/// @throw TypeError Casting to Type failed.
throw TypeError("Variable::value",
QString("Illegal type conversion to ") + typeid(Type).name());
}
return *v;
}

/**
* Returns the current mode flags of the variable.
*/
Expand Down
2 changes: 1 addition & 1 deletion doomsday/libcore/src/data/record.cpp
Expand Up @@ -704,7 +704,7 @@ Record const &Record::parentRecordForMember(String const &name) const
if(lastOmitted.isEmpty()) return *this;

// Omit the final segment of the dotted path to find out the parent record.
return (*this)[lastOmitted].valueAsRecord();
return (*this)[lastOmitted];
}

QTextStream &operator << (QTextStream &os, Record const &record)
Expand Down
10 changes: 10 additions & 0 deletions doomsday/libcore/src/data/variable.cpp
Expand Up @@ -167,11 +167,21 @@ Value const *Variable::valuePtr() const
return d->value;
}

Record &Variable::valueAsRecord()
{
return value<RecordValue>().dereference();
}

Record const &Variable::valueAsRecord() const
{
return value<RecordValue>().dereference();
}

Variable::operator Record & ()
{
return valueAsRecord();
}

Variable::operator Record const & () const
{
return valueAsRecord();
Expand Down

0 comments on commit a4f87b9

Please sign in to comment.