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();
}
C++ is the glamourous rockstar that everyone pays attention to. C is her plain-looking older sister that does all of the songwriting :(
The way I mean it is that, generally, C++ is a language that works "with the metal", whereas Javascript works with a context (Usually a DOM of some sort, though Node mixes that up a bit).
Of course, generally speaking, any scripting language is a programming language. I just tend to make a clear distinction between them and languages like C++, Java or C#.