Now that I have free time again for my own programming projects, I decided to start working on games again, and thus on my game engine.
My current goal is to transfer the gameplay from that puzzle/RPG game that I was working on in collaboration (Which is on halt due to the guy I'm working with being bogged down by the German education system).So yeah, I'm quietly porting it to C++; we don't want to use GM for it, because it's damned messy. Anyway, the last blog I wrote about Singletons showed me doing it in the naive way: Manually creating classes 'as' a Singleton type by giving it specific properties. That works, but is a slog. Wouldn't it be far easier to just inherit some sort of global "Singleton" type and not have to do anything further? Well, we can. And it's easy too.There are two methods I'm going to address: One for those who like templates, and one for those who don't.The Template methodTemplates are a very powerful part of the C++ language… but in my personal opinion, they can also be messy, unwieldy abominations that make your code look like it fell part-way into a mincer.It all depends on how you use them, of course.Originally, I was just going to write the quick and dirty 'macro' technique, as below, but then on the spur of the moment I added this as an elegant alternative.template<class ATYPE>
class Singleton {
public:
static ATYPE & getInstance() {
static ATYPE singleton_instance;
return singleton_instance;
}
};
class Tester : public Singleton<Tester> {
private:
Tester(){} // Prevent construction
public:
void doSomething() {
printf("Something is being done\n");
}
};
int main(int argc, char** argv) {
Tester::getInstance().doSomething();
}
#define INST(singleton) (singleton::getInstance())
int main(int argc, char** argv) {
INST(Tester).doSomething();
}
#define DECL_SINGLETON(stype) static stype & getInstance() { static stype singleton; return singleton; }
#define INST(singleton) ((singleton&) singleton::getInstance())
class Test2 {
private:
Test2(){}
public:
void doSomething() {
printf("Something else is being done!\n");
}
DECL_SINGLETON(Singleton)
};
int main(int argc, char** argv) {
INST(Test2).doSomething();
}
Glad you've returned *from hell*. :) Neat, is all I can say. In this case I definitely prefer the template method.
Reading someone's C++ code makes me want to code in C++, too. But when I try to program something in C++, it takes a few moments until I realize why I prefer JavaScript…
It's hardly right to compare JavaScript and C++. They're two completely different things. C++ is a programming language, JavaScript is a scripting language.
On that note, I'm working on a module to include JavaScript as a viable scripting language for this engine.C++ disgusts me, all the ** and the ::
Hideous.But I should probably learn what those mean and give it a chance.C++ is too spooky for me. I'll just stay with C#… for now.
I like C++ the way it is :(