Greetings fellow programmers,
I'm going to head straight to the point.
First of all, here's the full source:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#ifndef __C_GENERIC_FACTORY_H
#define __C_GENERIC_FACTORY_H
#include <string>
#include <map>
namespace Factory
{
template<class T>
class CGenericFactory
{
typedef T* (*tCreator)();
typedef std::map<std::string, tCreator> tStringCreatorMap;
public:
CGenericFactory();
~CGenericFactory();
bool Register(const char* id, tCreator creator);
T* Create(const char* id);
private:
tStringCreatorMap m_CreatorMap;
};
template<class T>
CGenericFactory<T>::CGenericFactory()
{
}
template<class T>
CGenericFactory<T>::~CGenericFactory()
{
}
template<class T>
bool CGenericFactory<T>::Register(const char* id, tCreator creator)
{
return m_CreatorMap.insert(tStringCreatorMap::value_type(std::string(id), creator)).second;
}
template<class T>
T* CGenericFactory<T>::Create(const char* id)
{
tStringCreatorMap::iterator i = m_CreatorMap.find(std::string(id));
if(i != m_CreatorMap.end())
{
return i->second();
}
else
{
return NULL;
}
}
}
#endif
|
As you can see, CGenericFactory is a template class whose purpose is mapping string identifiers with "creator" functions so as to dynamically create instances of certain classes. The implementation of this class is not this post's topic.
Moving on, I get the following errors:
1 2 3 4
|
|--|In member function ‘T* Factory::CGenericFactory<T>::Create(const char*)’:|
|43|error: expected `;' before ‘i’|
|44|error: ‘i’ was not declared in this scope|
||=== Build finished: 2 errors, 0 warnings ===|
|
What one can conclude from this build log is that Mr.GNU Gcc Compiler believes that Mrs.STL Map's iterator is not a class, but an instance. As expected, the code with these changes compiles with no problems:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
...
template<class T>
T* CGenericFactory<T>::Create(const char* id)
{
tStringCreatorMap::iterator = m_CreatorMap.find(std::string(id));
if(tStringCreatorMap::iterator != m_CreatorMap.end())
{
return tStringCreatorMap::iterator->second();
}
else
{
return NULL;
}
}
...
|
Sadly, this doesn't make any sense, given that an iterator belonging to a given class is supposed to be yet another class from which several instances can be created. What's wrong here? "Am I going crazy or is this just a dream?"
Best Regards,
Deimos