Skip to main content
gamedev.net
🔒 Locked

C++ variable passing

Started by Lemon_ 2 replies 600+ views
Original Post
Lemon_
Lemon_
Writing a simple Debugging console for my current project and ran into a little problem. Usually I find myself writing the line cout << "Direction = " << d << "\n"; which I would rather replace with a line such as Debug.println("Direction",d); My problem is this: How do I pass in the variable d to my Debug class? I'm used to java with its everything extends the Object class structure. In java I would simply make the method println take an Object as a parameter then print this out. Attempting to follow this convention I tried using a void pointer but this only results in the data's reference being printed out. My next guess was that the method should take in an ostream object. This leads to a nasty style of" ostream os; os << d; Debug.println("Direction",os); which is hardly simplifying anything. I'm all confused, is there not a simple way to do this? Thanks in advanced Simon
Aardvajk
Aardvajk
You could use a template if you only ever want one parameter:

#include <iostream>#include <string>using namespace std;class Debug{private:    ostream &os;public:    Debug(ostream &o) : os(o) { }    template<class T> void Out(const string &s,const T &t)        { os << s << t << endl; }};Debug d(cout);void f(){    d.Out("Integer - ",10);    d.Out("String - ","This is a string");    d.Out("Float - ",0.345f);    // and so on for anything that can be passed to ostream<<}
iMalc
iMalc
Ah, so you'd like to leave the happy world of type safety?
Try asking Zahlman about his sig...[grin][lol]
Lemon_
Lemon_
Ok thanks, I shall give that a go. :D

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.