Skip to content

Instantly share code, notes, and snippets.

@malleor
Created May 29, 2012 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malleor/2828959 to your computer and use it in GitHub Desktop.
Save malleor/2828959 to your computer and use it in GitHub Desktop.
Generic factoring
class IFactory
{
public:
virtual ~IFactory() {}
/// Creates data object of the specified type
template <class DataType>
DataType* CreateData()
{
return NULL;
}
template <>
int* CreateData<int>()
{
return CreateInt();
}
/// Deletes specified data object
template <class DataType>
void DeleteData(DataType* p_data_object)
{
}
template <>
void DeleteData<int>(int* p_data_object)
{
DestroyInt(p_data_object);
}
virtual int* CreateInt() = 0;
virtual void DestroyInt(int*) = 0;
};
class Factory : public IFactory
{
public:
virtual int* CreateInt()
{
return new int[2];
}
virtual void DestroyInt(int* p)
{
delete[] p;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
IFactory* f = new Factory;
int* a = f->CreateData<int>();
float* b = f->CreateData<float>();
f->DeleteData(a);
f->DeleteData(b);
delete f;
return 0;
}
@malleor
Copy link
Author

malleor commented May 29, 2012

Or maybe we should make the IFactory simple with virtual creators only and make templates global utilities taking factory as argument? This would follow Meyers' 'Strive for interfaces that are minimal and complete.'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment