• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
nuclear123

how to return different types?

7 posts in this topic

does anyone have any recommendations or advice on how i would do the following. Pretty much i want a function to possibly return 2 different types of structs depending on the XML it is parsing


struct Error
{
string errorMessage;
string otherinfo;

}

struct Person
{
string firstname;
string lastname;
int age;
float height;
}

Error/Person ParseXML(string XML)
{
if (<person>)
return parsePerson(XML); // return a Error object
else
return parseError(XML); // return a person object

}
0

Share this post


Link to post
Share on other sites
You probably want to switch to inherited classes. Either way, you're going to need to return a pointer instead of the struct itself. First, you'll probably want some way to tell which one is returned, so you should add an integer called type or something first in your structs. Then, make a third struct, called simply XMLReturn or something, that contains only the type variable. Have your function return a pointer of that type, and then just, return whichever struct you allocate normally. You can read the type of your XMLReturn variable and decide what to cast it back to.
0

Share this post


Link to post
Share on other sites
struct typea
int type
String something

Struct typeb
int type
float somenumber

Struct basetype
int type

basetype* function
if something
typea *ret=malloc(typea) ;
ret.type=1
return ret


basetype *xml=function ()
if xml.type=1
typea *a=(typea*) xml
-1

Share this post


Link to post
Share on other sites
That looks incredibly messy and like the equivalent of constantly abusing dynamic_casts in C++ to check types. It seems like conceptual nonsense to be "deriving" unrelated things like Person and Errors from one base and introduce the mess of dynamically allocating/deallocating objects (especially after all the wild brute force casting) to implement the misguided idea of a single function returning completely different types of objects. Sometimes the question isn't "how can I do this", but "why on earth would I WANT to do this".

Either do what tons of C libraries do and have functions always return an error code while using an output parameter for your data, which will look like this

[code]
Person person;
Error error = parseXML(xml, &person);
[/code]


or return a (well defined) dummy Person on error and set a global error object (C typically does both, with functions returning -1 on error and additionally setting the global error number, a completely separate function will then map error codes to error strings). Of course a global error has other problems of its own (not thread safe, the next call might overwrite your previous error, etc.)

In C++ you could use exceptions for errors, which makes some things very convenient (if your calls go through several levels, you don't have a dozen places to do error checking), but also a little messy (you need to learn writing exception safe code and all the try/catch can go a little out of hand).
-1

Share this post


Link to post
Share on other sites
This is all im trying to do:
1.) Have a function that can detect and effectively parse 2 diffrent possible XML messages. Upon return the XML we be stored in the appropriate struct and returned by the function. I can then have the caller somehow know the type that was returned and handle the struct according to its type. Here is my code if this helps


[CODE]
QList<CError> ParseError(QXmlStreamReader& streamReader)
{
QList<CError> errorList;
CError errorBuffer;

streamReader.readNext();
while (!(streamReader.tokenType() == QXmlStreamReader::EndElement && streamReader.name() == "ErrorMessage")) {
if (streamReader.tokenType() == QXmlStreamReader::StartElement) {
if (streamReader.name() == "Title") {
errorBuffer.strTitle = streamReader.readElementText();
}
if (streamReader.name() == "Message") {
errorBuffer.strMessage = streamReader.readElementText();
}
}
streamReader.readNext();
}
errorList.append(errorBuffer);
return errorList;
}

QList<CSubscription> ParseSubscription(QXmlStreamReader& streamReader)
{
QList<CSubscription> subscriptionList;
CSubscription subscriptionBuffer;

streamReader.readNext();
while (streamReader.tokenType() != QXmlStreamReader::EndDocument) {
while (!(streamReader.tokenType() == QXmlStreamReader::EndElement && streamReader.name() == "Subscription")) {
if (streamReader.tokenType() == QXmlStreamReader::StartElement) {
if (streamReader.name() == "NewestVersion") {
subscriptionBuffer.strNewestVersion = streamReader.readElementText();
}
if (streamReader.name() == "ProductName") {
subscriptionBuffer.strGame = streamReader.readElementText();
}
if (streamReader.name() == "ExpiryDate") {
subscriptionBuffer.strExpireDate = streamReader.readElementText();
}
if (streamReader.name() == "Detection") {
subscriptionBuffer.strDetection = streamReader.readElementText();
}
}
streamReader.readNext();
}
subscriptionList.append(subscriptionBuffer);
}
return subscriptionList;
}


QList<EITHERSTRUCT> ParseXML(QString& strXML)
{
QXmlStreamReader streamReader(strXML);

while (!streamReader.atEnd()) {
QXmlStreamReader::TokenType token = streamReader.readNext();
if(token == QXmlStreamReader::StartDocument) {
continue;
}
if(token == QXmlStreamReader::StartElement) {
if (streamReader.name() == "ErrorMessage") {
return ParseError(streamReader);
}
if (streamReader.name() == "Subscription") {
return ParseSubscription(streamReader);
}
}
}
return SOME_ERROR;
}[/CODE]
0

Share this post


Link to post
Share on other sites
Make a function to get the type of the data and then call geterror or getplayer, whichever is the right one, passing them the xml already parsed by the gettype thing hopefully (figure out better names for them)

0

Share this post


Link to post
Share on other sites
What you are after is a factory pattern and most of those in C++ require RTTI in some way or other. I use class registrars to collect the creation functions at compile time to create objects from a factory [url="http://code.google.com/p/dxengine/source/browse/trunk/src/ClassRegistration.h"]http://code.google.c...sRegistration.h[/url], [url="http://code.google.com/p/dxengine/source/browse/trunk/src/RTTI.h"]http://code.google.com/p/dxengine/source/browse/trunk/src/RTTI.h[/url], [url="http://code.google.com/p/dxengine/source/browse/trunk/src/RTTIMacros.inl"]http://code.google.com/p/dxengine/source/browse/trunk/src/RTTIMacros.inl[/url]. But I think you can do this with a templated factory as well h[url="http://stackoverflow.com/questions/5185502/template-factory-pattern-in-c"]ttp://stackoverflow...ry-pattern-in-c[/url]
0

Share this post


Link to post
Share on other sites
One idea is to return a tuple of optional Person, Error:
[code]
template<typename T>
struct ParseResult {
boost::optional<T> success;
boost::optional<Error> error;

ParseResult(const T &success) {
// ...
}

ParseResult(const Error &error) {
// ...
}
};
[/code]
The caller can inspect the optional values to determine which value was returned. A more generalised version of this is boost::variant, or in extreme cases boost::any. I'm not aware of these types being included in C++0x.

If the file contains many objects, the above could be two containers:
[code]

template<typename T>
struct ParseResults {
std::vector<T> successes;
std::vector<Error> errors;
};
[/code]
If the order is important (e.g. parsing a list of elements and you want to correlate errors with particular entries) then you can store the index in the vectors too.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0