I have a legacy interface that gives me the type to instance under the form of a string, for example “int”, “float”, etc.
I’ve came up with these two functions to solve the problem:
template <typename T>
T type_factory(const std::string& type_id)
{
if (!type_id.compare("long"))
{
long res;
return res;
}
if (!type_id.compare("double"))
{
double res;
return res;
}
if (!type_id.compare("char"))
{
char res;
return res;
}
}
and
template <class PointerClass, typename T>
PointerClass<T>* pointer_factory(void* ptr, T dummy_type)
{
return static_cast<PointerClass<T>*>(ptr);
}
//Desidered usage:
//void* raw_ptr;
//Calculator<int>* p = pointer_factory<Calculator>(raw_ptr, type_factory("int"));
The second function doesn’t compile the error is “expected unqualified-id” near PointerClass.
Could someone please tell me why the second function does not compile and how to fix it?
Thanks in advance.
Seems like you need a template template:
instead of
since
PointerClassis itself a template.This fixes the compilation error, you’ll have to test if it does what you want yourself, though I doubt it will.
EDIT:
Seems like a factory class, instead of templates, might be easier to write and understand by others in this case.