I am trying to make a framework in C++ using Visual Studio 2010 where I can create objects at the same time as class definition of lots of derived classes. I have been reading a bit on this, and understand the the factory pattern can be used. I however do not manage to get it working.
I have the following code:
#include <stdio.h>
#include <iostream>
#include <vector>
class TestCase;
std::vector<TestCase*> testcases;
class base
{
public:
static void init();
};
template<class T>
class TestcaseFactory// : public base
{
public:
TestcaseFactory()
{
testcases.push_back(new T());
}
private:
};
class TestCase
{
public:
virtual void id() = 0;
};
#define TESTCASE(derived)\
class derived; \
TestcaseFactory<derived> testcase_##derived(); \
class derived : public TestCase
TESTCASE(derived1)
{
void id() {std::cout << "derived 1" << std::endl;}
};
TESTCASE(derived2)
{
void id() {std::cout << "derived 2" << std::endl;}
};
int main()
{
for(unsigned int i = 0; i < testcases.size(); ++i)
{
std::cout << i << std::endl;
testcases[i]->id();
}
getchar( );
}
and would have expected the loop in main()
to call the two created objects and print
derived1
derived2
However nothing happens. For some reason the code in the #define
is never reached. I can not figure out why?