1

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.

6
  • 1
    The first function is not correct. There is no type T that is a supertype of long, double and char. Commented Mar 22, 2012 at 10:15
  • First of all, don’t use compare. Use == instead! Commented Mar 22, 2012 at 10:15
  • @LucaMartini: You're right. It was a quick hack to poke around with the subject, but if I have to specify the type it's pretty useless though. Commented Mar 22, 2012 at 10:26
  • @KonradRudolph: Could you please tell my why? Commented Mar 22, 2012 at 10:26
  • 1
    @KonradRudolph compare does not create a temporary std::string, so I believe in this case it can be better to avoid operator== Commented Mar 22, 2012 at 10:31

1 Answer 1

2

Seems like you need a template template:

template < template<typename T> class PointerClass, typename T>
PointerClass<T>* pointer_factory(void* ptr, T dummy_type) 

instead of

template <class PointerClass, typename T>
PointerClass<T>* pointer_factory(void* ptr, T dummy_type)

since PointerClass is 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks everyone, I have not finished here but I'm a bit closer to what I want to accomplish :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.