|
/**
* This code is a supplement to the article
* 'RAII, Dynamic Objects, and Factories in C++'
* at CodeProject: http://www.codeproject.com/
*/
#include <iostream>
#include "gfactory.h"
#include "myclass.h"
#include "myhierarchy.h"
#if (defined __BORLANDC__)
# pragma warn -8004 // never used values
#endif
#if defined _MSC_VER
# define for if(0);else for //MSDN KB167748
#endif
using namespace std;
inline void doSomething (MyClass& m) { m.set (m.get()); }
/**
* simple demo for the 'standard' RAII factory
*/
void testRaiiFactory() {
cout << "testRaiiFactory() ..." << endl;
MyClassFactory mcf;
// MyClassFactory mcf2 = mcf; // ok, does not compile
// test create functions
for (int i = 0; i < 10; ++i) {
MyClass* p = mcf.create();
doSomething (*p);
p = mcf.create (i);
doSomething (*p);
p = mcf.create (i*7.03);
doSomething (*p);
p = mcf.create ("test");
doSomething (*p);
p = mcf.create (i, i*7.03);
doSomething (*p);
if (i % 3) {
mcf.dispose (p);
}
}
// test operator[]
for (size_t i = 0; i < mcf.size(); ++i) {
doSomething (*mcf[i]);
MyClass* p = mcf[i];
const MyClass* cp = mcf[i];
}
// test const
const MyClassFactory& rcf = mcf;
const MyClass* cp = rcf[0];
}
/**
* demo for Generic RAII Factory: RAII factory usable without writing glue code.
* Hint for VC++ 6.0: the compiler sometimes reports an 'ambiguous call to overloaded
* function'. Workaround: cast argument, e.g.
* p = mcf.create ((int) i);
* see also: KB240869 http://support.microsoft.com/kb/240869/
*/
void testGenericRaiiFactory() {
cout << "testGenericRaiiFactory() ..." << endl;
GFactory<MyClass> mcf;
for (int i = 0; i < 10; ++i) {
MyClass* p = mcf.create();
doSomething (*p);
p = mcf.create (i);
doSomething (*p);
p = mcf.create (i*7.03);
doSomething (*p);
p = mcf.create ("test");
doSomething (*p);
p = mcf.create (i, i*7.03);
doSomething (*p);
}
}
#if !(defined (_MSC_VER) && _MSC_VER <= 1200) // not MSVC++ 6.0
/**
* create base and derived objects with one RAII factory
*/
void testPolymorphicRaiiFactory() {
cout << "testPolymorphicRaiiFactory() ..." << endl;
MyPolymorphicFactory polyFactory;
MyBase* object = polyFactory.create<MyBase>();
object = polyFactory.create<MyBase> (33);
object = polyFactory.create<MyDerived>();
object = polyFactory.create<MyDerived> (77);
}
#else
#pragma message ("explicit function template argument specification not supported in VC++ 6.0!")
#endif
// --------------------------------------------------------
int main() {
cout << endl;
testRaiiFactory();
testGenericRaiiFactory();
#if ! (defined (_MSC_VER) && _MSC_VER <= 1200)
testPolymorphicRaiiFactory();
#endif
cout << endl;
return 0;
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.