Created
May 29, 2012 15:10
-
-
Save malleor/2828959 to your computer and use it in GitHub Desktop.
Generic factoring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.'