Limiting includes in C++ - c++

I am having all sorts of problems with include-overload in my newbie C++ project, but I'm not sure how to avoid it.
How do I avoid the problem of having to include dozens of classes, for example in a map-loading scenario:
Here's a trivial example Map class, which will load a game-map from a file:
// CMap.h
#ifndef _CMAP_H_
#define _CMAP_H_
class CMap {
public:
CMap();
void OnLoad();
};
#endif
// CMap.cpp
#include "CMap.h"
CMap::CMap() {
}
void CMap::OnLoad() {
// read a big file with all the map definitions in it here
}
Now let's say I have a whole plethora of monsters to load into my map, so I might have a list or some other structure to hold all my monster definitions in the map
std::list<CMonster*> MonsterList;
Then I could simple forward-declare "CMonster" in my CMap.h, and add as many monsters as I like to that list
// CMap.h
class CMonster;
// CMap.cpp
void CMap::OnLoad() {
// read a big file with all the map definitions in it here
// ...
// read in a bunch of mobs
CMonster* monster;
MonsterList.push_back(monster);
}
But what if I have lots of different types of monster? How do I create lots of different types of monster without including every CMonster_XXX.h? And also use methods on those?
// CMap.cpp
void CMap::OnLoad() {
// read a big file with all the map definitions in it here
// ...
// read in a bunch of mobs
CMonster_Kitten* kitty;
kitty->OnLoad();
MonsterList.push_back(kitty);
CMonster_Puppy *puppy;
puppy->OnLoad();
puppy->SetPrey(kitty);
MonsterList.push_back(puppy);
CMonster_TRex *awesome;
awesome->OnLoad();
awesome->SetPrey(puppy);
MonsterList.push_back(awesome);
}

Here's the rule I use for including things.
Forward declare as much as you can in your header files.
include any .h you need in your .cpp
don't include .h in other .h unless you have to.
If your project build without needing to include a .h, you are fine. (mostly, provided your compiler is compliant enough)
Edit: Additionally, you may want to read Large-Scale C++ Software Design. It talks about managing physical file dependencies.

You could create a file myMonstersInclude.h like
#include "myMonster1.h"
#include "myMonster2.h"
....
Your main code will only need to do `#include "myMonstersInclude.h".
You could even generate it using your build tools, most allow you to run your own script before and after every step.

Short answer is: You can't.
Slightly longer is: You can create a header file that just #includes the other ones, and include the new header file in your .cpp files. This is still effectively including all the headers though, you just don't have the list of includes duplicated, which is why I said the shorts answer is you can't.
The new header would something like:
#include CMonster_cat
#include CMonster_puppy
...

The question is, does your map really need to know about all the individual types of monsters? Probably not - just knowing that they derive from CMonster should be enough as far as the map is concerned. All the methods that your map class uses should be able to operate through virtual functions on the monsters, so each monster type defines its specialized behavior, not the map.
I suspect your "include problem" will be greatly reduced by making proper use of inheritance here.

You could use a factory function. Combined with global static objects to register the types. Something like this:
// in some main file...
typedef CMonster*(*create_ptr)();
std::map<std::string, create_ptr> &get_map() {
// so we can make sure this exists...
// NOTE: we return a reference to this static object
static std::map<std::string, create_ptr> map;
return map;
}
we add some glue code to register a creation function...
// in each type of monster class (ex: CMonsterA)
CMonster *create_monster_a() {
return new CMonsterA;
}
static struct monsterA_Registrar {
monsterA_Registrar() {
get_map().insert(std::make_pair("MonsterA", create_monster_a));
}
} register_monsterA;
finally, back in the main file, you can create a monster object by the name of it's type...
std::map<std::string, create_ptr>::iterator it = get_map().find("MonsterA");
if(it != get_map().end()) {
return (it->second)();
}
throw "invalid monster type requested";
Here's what is happening:
When the program starts, before main, it will run all constructors of global objects, in this case register_monsterA is one of them.
This object's constructor will get get_map() (it can't just be a global static because we have no way of knowing what order things get initialized in if we do, so it's a function).
Then it will add an item to it which is a "creation function", basically a function which is capable of making a new CMonster.
Finally, to make a monster, we just look in that same map, and get the creation function and run it (if it was present).
EDIT: Here's a complete working example... (with some macro magic to make it cleaner)
CMonster.h
class CMonster {
public:
virtual ~CMonster() {
}
virtual void roar() = 0;
};
typedef CMonster*(*create_ptr)();
std::map<std::string, create_ptr> &get_map();
#define MONSTER_REGISTRAR(name) \
CMonster *create_monster_##name() { \
return new C##name; \
}\
\
static struct monster##name##_Registrar {\
monster##name##_Registrar() { \
get_map().insert(std::make_pair(#name, create_monster_##name));\
} \
} register_monster##name;
CMonster.cc
std::map<std::string, create_ptr> &get_map() {
// so we can make sure this exists...
// NOTE: we return a reference to this static object
static std::map<std::string, create_ptr> map;
return map;
}
CMonsterA.cc
#include "CMonster.h"
class CMonsterA : public CMonster {
public:
CMonsterA() {
std::cout << "HERE - A" << std::endl;
}
virtual void roar() {
std::cout << "A" << std::endl;
}
};
MONSTER_REGISTRAR(MonsterA)
CMonsterB.cc
#include "CMonster.h"
class CMonsterB : public CMonster {
public:
CMonsterB() {
std::cout << "HERE - B" << std::endl;
}
virtual void roar() {
std::cout << "B" << std::endl;
}
};
MONSTER_REGISTRAR(MonsterB)
main.cc
#include "CMonster.h"
CMonster *get_monster(const std::string &name) {
std::map<std::string, create_ptr>::iterator it = get_map().find(name);
if(it != get_map().end()) {
return (it->second)();
}
throw "invalid monster type requested";
}
int main() {
CMonster *monster = get_monster("MonsterB");
monster->roar();
delete monster;
}

Related

Automatically register new derived class / creator method

I guess it'll be easiest if I give an example of what I'm trying to achieve.
Let's say I'd like to implement a unit testing environment, in which implementing a new unit test would involve deriving from a given base class and (possibly) following guidlines involving putting additional macros. Such new test would then be automatically added to list of tests, ran one after another at some point. Two things however:
I'm trying to make creating each new test as quick and easy as possible, especially when it comes to modifying files other than the files with the test itself. A perfect situation would be such, that implementing a new test wouldn't require touching any other files in the project. This is achievable with singletons and possibly CRTP, but now comes point number 2,
The target is an MCU with limited amount of RAM (ROM in general is not a problem) and I'd like to be able to run the tests directly on the target platform. Because of this, static objects occupying memory throughout the entire application lifetime are not acceptable. Instead, I'd like to be able to create and delete each test separately only at the time it needs to be ran.
Basically, the problem comes down to a way of automatically registering derived types - or creator methods - to a factory with minimum RAM overhead (I'm assuming there will be some, i.e. at least pointers to said methods).
Sorry for no code samples, but there's really nothing to show here without already committing to one given implementation.
Could you create a static/global vector of function pointers. These would be pointers to creator/factory functions for each test class. The factory functions return pointers to the base test class. I was going to try to write it out, but I think code is easier to write and understand.
class TestBase
{
public:
static char registerTest(<function ptr type> creator) {
testCreators.push_back(creator);
return 1;
}
static void runTests()
{
for (auto creator : testCreators)
{
auto newTestClass = creator();
newTestClass->tests();
delete newTestClass;
}
}
private:
void tests() = 0;
std::vector<function ptr type> testCreators;
};
Then the derived class.
class SpecificTest : public TestBase
{
// Pretend test code is here.
private:
static char dummy;
};
// Plan old C function. Need to establish naming conventions so as
// not to get multiple symbol errors during linking. Kind of fragile.
TestBase* specificTestCreator()
{
return new SpecificTest();
}
In the .cpp file for SpecificTest
char SpecificTest::dummy = TestBase::registerTest(specificTestCreator);
I have tried to compile or run this, but I think it's fundamentally sound.
I've created an example based on the answer provided by Michael, compiled and ran it. Posting code below.
TestBase.h:
#ifndef TESTBASE_H_
#define TESTBASE_H_
#include <vector>
class TestBase {
public:
TestBase();
virtual ~TestBase();
static void RunAllTests();
protected:
virtual void test() = 0;
static char addTestCreator(TestBase* (*creator)());
private:
static std::vector<TestBase* (*)()> &getTests();
};
#endif /* TESTBASE_H_ */
TestBase.cpp
#include "TestBase.h"
TestBase::TestBase() {
}
TestBase::~TestBase() {
}
char TestBase::addTestCreator(TestBase* (*creator)())
{
getTests().push_back(creator);
return 0;
}
void TestBase::RunAllTests()
{
for(std::vector<TestBase* (*)()>::iterator it = getTests().begin(); it != getTests().end(); it++)
{
TestBase *t = (*it)();
t->test();
delete t;
}
}
std::vector<TestBase* (*)()> &TestBase::getTests()
{
static std::vector<TestBase* (*)()> v;
return v;
}
ConcreteTest1.h:
#ifndef CONCRETETEST1_H_
#define CONCRETETEST1_H_
#include "TestBase.h"
class ConcreteTest1: public TestBase {
public:
ConcreteTest1();
virtual ~ConcreteTest1();
protected:
void test();
private:
// both here can be expanded with a macro to make it
// easier as they'll be same for all derived classes
static char dummy;
static TestBase *creator();
};
#endif /* CONCRETETEST1_H_ */
ConcreteTest1.cpp:
#include "ConcreteTest1.h"
#include <iostream>
// can be expanded with a macro
char ConcreteTest1::dummy = TestBase::addTestCreator(ConcreteTest1::creator);
// can be expanded with a macro
TestBase* ConcreteTest1::creator()
{
return new ConcreteTest1();
}
ConcreteTest1::ConcreteTest1()
{
std::cout << "Creating test 1" << std::endl;
}
ConcreteTest1::~ConcreteTest1()
{
std::cout << "Deleting test 1" << std::endl;
}
void ConcreteTest1::test()
{
std::cout << "Running test 1" << std::endl;
}
Similarly ConcreteTest2.cpp/.h.
Invoked from main with:
TestBase::RunAllTests();
Output is:
Creating test 1
Running test 1
Deleting test 1
Creating test 2
Running test 2
Deleting test 2
which is exactly what I've wanted to achieve.

C++ code generation: create a factory for function pointers

I have a long and steadily growing list of (non-member) functions and I need to select one of the functions from this list at runtime (based on a command line argument). At the moment I do this using a factory function which takes a string (the name of the function) and returns a pointer to the function. However this means I have to edit the factory function every time I add a new function (which is both annoying and a violation of the DRY principle).
I would like to somehow generate the factory function by parsing the source code of the list of functions (inspired by reading the code generation section of The Pragmatic Programmer last night). However it seems that it is very hard to parse C++ correctly and I would rather not make my project depend on libclang just for this.
So my question is: how can I select a function by name at runtime without introducing heavyweight dependencies?
Is it "safe" to only partially parse the c++ code (e.g. just using a regex to extract function names by matching something that looks like a set of function arguments)?
Are there any other (portable and not too hacky) ways of doing this without manually writing the selection code?
edit: Forgot to say: I'm not allowed to use C++11, so no lambda functions unfortunately.
Here is a fully working example :
#include <iostream>
#include <map>
namespace detail {
struct FuncPtrMap {
friend struct FuncPtrRegisterer;
using FuncPtr = void(*)();
static std::map<std::string, FuncPtr> const &getMap() {
return getWritableMap();
}
private:
// SIOF-proof singleton
static std::map<std::string, FuncPtr> &getWritableMap() {
static std::map<std::string, FuncPtr> theMap;
return theMap;
}
};
// Each static instance will register one function pointer
struct FuncPtrRegisterer {
FuncPtrRegisterer(FuncPtrMap::FuncPtr funcPtr, char const *funcName) {
FuncPtrMap::getWritableMap().emplace(funcName, funcPtr);
}
};
}
// Public access to the function pointers map
auto const &gFunctionPointersMap = detail::FuncPtrMap::getMap();
#define DO_CAT(A, B) A##B
#define CAT(A, B) DO_CAT(A, B)
// Registering macro : defines a static registerer
// with a (hopefully) unique name.
#define REGISTER_FUNC(NAME) detail::FuncPtrRegisterer \
CAT(fpreg, __COUNTER__) (&NAME, #NAME)
//
// Test
//
void myFunc1() {
std::cout << "func1\n";
}
REGISTER_FUNC(myFunc1);
void myFunc2() {
std::cout << "func2\n";
}
REGISTER_FUNC(myFunc2);
int main()
{
for(auto const &kv : gFunctionPointersMap) {
std::cout << "Calling " << kv.first << " : ";
kv.second();
}
return 0;
}
Prints :
Calling myFunc1 : func1
Calling myFunc2 : func2
Just put a REGISTER_FUNC(func) after each function you wish to register. You only need the declaration of the function, not its definition. Beware that this will not work in header files though.
Afterwards, you can access gFunctionPointersMap at any time from the very start of main :)
Edit : C++03 version here (nothing much changes really).

Registering classes/functions/things before main()

Suppose I have a class called Poem.
class Poem{
virtual void recite() = 0;
}
And I have hundreds of .cpp and .hpp files which describe a subclass, like the following
class TheRaven : public Poem{
void recite() { std::cout << "NEVERMORE!" << endl; }
}
And the likes. And in the main function, I'd like to be able to just iterate through every single possible Poem subclasses and call their recite() function. So I made a class:
class PoemRegistry{
std::map<std::string, Poem*> poems;
PoemRegistry& getGlobal(); // returns a static global registry
void register(const std::string& poemname, Poem * thepoem);
};
And then for each poem subclass .cpp file, I put the following.
class TheRavenRegistor{
TheRavenRegistor(){
PoemRegistry::getGlobal().register("theraven", new TheRaven());
}
}
TheRavenRegistor registor();
ninja edit: I put the global class there, forgot about it
Making it easy, I make a shortcut with #define and templates.
Now, the question is, I just heard about the static class initialization fiasco. I suppose this will be immune against it, or is there something I am definitely missing here? Or is there something more elegant that can be used for this purpose?
This is an example for the Singleton design pattern. Don't use a static global, since the initialisation order is undefined across compilation units.
Instead use something like this:
PoemRegistry& PoemRegistry::getGlobal()
{
static PoemRegistry theRegistry; // construction guaranteed when first call
return theRegistry;
}
Make the getGlobal() method static:
class PoemRegistry
{
public:
static PoemRegistry& getGlobal();
...

Map functions of a class while declaring the functions

My previous question about this subject was answered and I got some tests working nice.
Map functions of a class
My question is now, if there is a way to while declaring the function, be able to register it in a map, like I realized in this question about namespaces and classes:
Somehow register my classes in a list
the namespaces and classes was fine to register in a map using the "static" keyword, with that, those static instances would be constructed before the main() be called.
Can I do that somehow with class functions?
because when I use static keyword inside a class declaration, I can't initialize the member as I can outside the class declaration(as with namespaces and classes in the second url above)
I guess I could hardcode all members inside the constructor and register them in a map, but I would like to know if there is a way to do that while I declare the members, to make it easier in the future
Thank you,
Joe
What is your problem here ?
The problem is that, unfortunately, in C++ functions are not considered first class members.
Oh sure there are those pointers to functions that work pretty well, but there is no generic function type or anything like that.
There are however ways to work around this, the simplest I think being the Command pattern.
In the Command pattern a function (operation) is abstracted away in an object. The arguments are stored in the object for later reuse (for example undo or redo command) and a unified interface exists to perform the operation itself.
Less talk, more code:
class Command
{
public:
virtual ~Command() {}
virtual Command* clone() const = 0;
virtual void execute() = 0;
};
Simple ?
class Foo {};
class FooCommand: public Command
{
public:
void parameters(Foo& self, int a, std::string const& b);
virtual FooCommand* clone() const;
virtual void execute();
private:
Foo* m_self;
int m_a;
std::string const* m_b;
};
Now, the sweet thing is that I can simply store my command in a map.
// registration
typedef boost::ptr_map<std::string, Command> commands_type;
commands_type commands;
commands.insert("foo", FooCommand());
// get the command
Foo foo;
FooCommand* cFoo = dynamic_cast<FooCommand*>(commands["foo"].clone());
if (cFoo != 0)
{
cFoo->parameters(foo, 2, "bar");
cFoo->execute();
}
This proposal would still require some work.
passing the parameters is quite annoying since it requires a down cast.
I did not concern myself with exception safety, but returning an auto_ptr or a shared_ptr would be better for the clone method...
the distinction between a const and non-const Foo argument is not that easy to introduce.
However it is safer than using a void* to store the pointers to function in you map since you have the advantage of RTTI to check whether or not the type is correct.
On the other hand, printing the collection of Commands linked to a particular object is incredibly easy now (if you have one map per object), you can also find ways to emulate the effect of virtual methods etc...
But I hope you realize that you are in fact trying to implement reflection, and it's not gonna be easy... good luck!
You could use the preprocessor to allow code such as the following:
#include <iostream>
#include "Registration.h"
class myclass {
public:
myclass() { HANDLE_REGISTRATION(); }
private:
static void reg1() { std::cout << "reg1" << std::endl; }
static void reg2() { std::cout << "reg2" << std::endl; }
static void unreg() { std::cout << "ERROR!" << std::endl; }
BEGIN_REGISTRATION();
REGISTER(reg1);
REGISTER(reg2);
END_REGISTRATION();
};
int main()
{
myclass obj;
obj.callAllRegistered();
return 0;
}
The ugly preprocessor hacks are hidden away in Registration.h:
#ifndef INCLUDED_REGISTRATION_H
#define INCLUDED_REGISTRATION_H
#include <string>
#include <map>
#define BEGIN_REGISTRATION() \
std::map<std::string, void(*)()> reg; \
void register_static(const std::string& name, void(*f)()) \
{ \
reg[name] = f; \
} \
void registerAll() {
#define REGISTER(name) register_static(#name, name)
#define HANDLE_REGISTRATION() registerAll()
#define END_REGISTRATION() \
} \
public: \
void callAllRegistered() { \
std::map<std::string,void(*)()>::const_iterator it; \
for (it = reg.begin(); it != reg.end(); ++it) \
it->second(); \
} \
private: \
typedef int unusedblahblahblah___
#endif
What you are seeking is a principle called Reflection. Unfortunately, C/C++ does not provide this functionality, and implementing it in a C++ object would prove very complicated (if it's even possible).
If this functionality is needed, I would suggest looking at another language that supports metaprogramming features like this. Doing this exact thing is trivial in some other languages. For example, in Ruby you could say:
class Myclass
def initialize
end
def a
end
def b
end
end
x = Myclass.new
x.methods
=> ["inspect", "b", "clone", "taguri", "public_methods", "display", "instance_va
riable_defined?", "equal?", "freeze", "taguri=", "methods", "respond_to?", "dup"
, "instance_variables", "to_yaml_style", "__id__", "method", "eql?", "id", "sing
leton_methods", "send", "taint", "frozen?", "instance_variable_get", "__send__",
"instance_of?", "to_a", "type", "to_yaml_properties", "protected_methods", "obj
ect_id", "instance_eval", "==", "===", "instance_variable_set", "to_yaml", "kind
_of?", "extend", "to_s", "a", "hash", "class", "tainted?", "=~", "private_method
s", "nil?", "untaint", "is_a?"]
This will list all of the member functions (many of them are automatically-generated in this case) associated with the object. The same can be done for instance variables, etc. Many other languages offer these types of features.
If this feature is critical to what you are doing, then I would recommend that you re-examine your choice of programming language as you seem to be wanting to work on a higher level than C/C++ are typically designed for. It may be possible to shoehorn this sort of thing into C++ by using some sort of object/class generator pattern but it would not be trivial to write or to use the resulting classes.

How can I keep track of (enumerate) all classes that implement an interface

I have a situation where I have an interface that defines how a certain class behaves in order to fill a certain role in my program, but at this point in time I'm not 100% sure how many classes I will write to fill that role. However, at the same time, I know that I want the user to be able to select, from a GUI combo/list box, which concrete class implementing the interface that they want to use to fill a certain role. I want the GUI to be able to enumerate all available classes, but I would prefer not to have to go back and change old code whenever I decide to implement a new class to fill that role (which may be months from now)
Some things I've considered:
using an enumeration
Pros:
I know how to do it
Cons
I will have to update update the enumeration when I add a new class
ugly to iterate through
using some kind of static list object in the interface, and adding a new element from within the definition file of the implementing class
Pros:
Wont have to change old code
Cons:
Not even sure if this is possible
Not sure what kind of information to store so that a factory method can choose the proper constructor ( maybe a map between a string and a function pointer that returns a pointer to an object of the interface )
I'm guessing this is a problem (or similar to a problem) that more experienced programmers have probably come across before (and often), and there is probably a common solution to this kind of problem, which is almost certainly better than anything I'm capable of coming up with. So, how do I do it?
(P.S. I searched, but all I found was this, and it's not the same: How do I enumerate all items that implement a generic interface?. It appears he already knows how to solve the problem I'm trying to figure out.)
Edit: I renamed the title to "How can I keep track of... " rather than just "How can I enumerate..." because the original question sounded like I was more interested in examining the runtime environment, where as what I'm really interested in is compile-time book-keeping.
Create a singleton where you can register your classes with a pointer to a creator function.
In the cpp files of the concrete classes you register each class.
Something like this:
class Interface;
typedef boost::function<Interface* ()> Creator;
class InterfaceRegistration
{
typedef map<string, Creator> CreatorMap;
public:
InterfaceRegistration& instance() {
static InterfaceRegistration interfaceRegistration;
return interfaceRegistration;
}
bool registerInterface( const string& name, Creator creator )
{
return (m_interfaces[name] = creator);
}
list<string> names() const
{
list<string> nameList;
transform(
m_interfaces.begin(), m_interfaces.end(),
back_inserter(nameList)
select1st<CreatorMap>::value_type>() );
}
Interface* create(cosnt string& name ) const
{
const CreatorMap::const_iterator it
= m_interfaces.find(name);
if( it!=m_interfaces.end() && (*it) )
{
return (*it)();
}
// throw exception ...
return 0;
}
private:
CreatorMap m_interfaces;
};
// in your concrete classes cpp files
namespace {
bool registerClassX = InterfaceRegistration::instance("ClassX", boost::lambda::new_ptr<ClassX>() );
}
ClassX::ClassX() : Interface()
{
//....
}
// in your concrete class Y cpp files
namespace {
bool registerClassY = InterfaceRegistration::instance("ClassY", boost::lambda::new_ptr<ClassY>() );
}
ClassY::ClassY() : Interface()
{
//....
}
I vaguely remember doing something similar to this many years ago. Your option (2) is pretty much what I did. In that case it was a std::map of std::string to std::typeinfo. In each, .cpp file I registered the class like this:
static dummy = registerClass (typeid (MyNewClass));
registerClass takes a type_info object and simply returns true. You have to initialize a variable to ensure that registerClass is called during startup time. Simply calling registerClass in the global namespace is an error. And making dummy static allow you to reuse the name across compilation units without a name collision.
I referred to this article to implement a self-registering class factory similar to the one described in TimW's answer, but it has the nice trick of using a templated factory proxy class to handle the object registration. Well worth a look :)
Self-Registering Objects in C++ -> http://www.ddj.com/184410633
Edit
Here's the test app I did (tidied up a little ;):
object_factory.h
#include <string>
#include <vector>
// Forward declare the base object class
class Object;
// Interface that the factory uses to communicate with the object proxies
class IObjectProxy {
public:
virtual Object* CreateObject() = 0;
virtual std::string GetObjectInfo() = 0;
};
// Object factory, retrieves object info from the global proxy objects
class ObjectFactory {
public:
static ObjectFactory& Instance() {
static ObjectFactory instance;
return instance;
}
// proxies add themselves to the factory here
void AddObject(IObjectProxy* object) {
objects_.push_back(object);
}
size_t NumberOfObjects() {
return objects_.size();
}
Object* CreateObject(size_t index) {
return objects_[index]->CreateObject();
}
std::string GetObjectInfo(size_t index) {
return objects_[index]->GetObjectInfo();
}
private:
std::vector<IObjectProxy*> objects_;
};
// This is the factory proxy template class
template<typename T>
class ObjectProxy : public IObjectProxy {
public:
ObjectProxy() {
ObjectFactory::Instance().AddObject(this);
}
Object* CreateObject() {
return new T;
}
virtual std::string GetObjectInfo() {
return T::TalkToMe();
};
};
objects.h
#include <iostream>
#include "object_factory.h"
// Base object class
class Object {
public:
virtual ~Object() {}
};
class ClassA : public Object {
public:
ClassA() { std::cout << "ClassA Constructor" << std::endl; }
~ClassA() { std::cout << "ClassA Destructor" << std::endl; }
static std::string TalkToMe() { return "This is ClassA"; }
};
class ClassB : public Object {
public:
ClassB() { std::cout << "ClassB Constructor" << std::endl; }
~ClassB() { std::cout << "ClassB Destructor" << std::endl; }
static std::string TalkToMe() { return "This is ClassB"; }
};
objects.cpp
#include "objects.h"
// Objects get registered here
ObjectProxy<ClassA> gClassAProxy;
ObjectProxy<ClassB> gClassBProxy;
main.cpp
#include "objects.h"
int main (int argc, char * const argv[]) {
ObjectFactory& factory = ObjectFactory::Instance();
for (int i = 0; i < factory.NumberOfObjects(); ++i) {
std::cout << factory.GetObjectInfo(i) << std::endl;
Object* object = factory.CreateObject(i);
delete object;
}
return 0;
}
output:
This is ClassA
ClassA Constructor
ClassA Destructor
This is ClassB
ClassB Constructor
ClassB Destructor
If you're on Windows, and using C++/CLI, this becomes fairly easy. The .NET framework provides this capability via reflection, and it works very cleanly in managed code.
In native C++, this gets a little bit trickier, as there's no simple way to query the library or application for runtime information. There are many frameworks that provide this (just look for IoC, DI, or plugin frameworks), but the simplest means of doing it yourself is to have some form of configuration which a factory method can use to register themselves, and return an implementation of your specific base class. You'd just need to implement loading a DLL, and registering the factory method - once you have that, it's fairly easy.
Something you can consider is an object counter. This way you don't need to change every place you allocate but just implementation definition. It's an alternative to the factory solution. Consider pros/cons.
An elegant way to do that is to use the CRTP : Curiously recurring template pattern.
The main example is such a counter :)
This way you just have to add in your concrete class implementation :
class X; // your interface
class MyConcreteX : public counter<X>
{
// whatever
};
Of course, it is not applicable if you use external implementations you do not master.
EDIT:
To handle the exact problem you need to have a counter that count only the first instance.
my 2 cents
There is no way to query the subclasses of a class in (native) C++.
How do you create the instances? Consider using a Factory Method allowing you to iterate over all subclasses you are working with. When you create an instance like this, it won't be possible to forget adding a new subclass later.