Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a generic factory that creates an instance of some type

I need to create a factory function to create an instance that can accept any type with different number of arguments.

I’m having two classes Employee and contact and to create an instance for both classes by single factory function

I have no clue how to do that. help me to do that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Employee
{
    std::string m_name;
    int m_id;
    int m_salary{};

public:
    template<typename T1, typename T2>
    Employee(T1&& name, T2&& id, T2&& salary)
        : m_name{ std::forward<T1>(name) }, m_id{ id }, m_salary{ salary }
    {
        std::cout << "template Employee constructor" << std::endl;
    }
};

class Contact
{
    std::string m_name;
    long long int m_number;
    std::string m_address;
    std::string m_mail;

public:
    template<typename T1, typename T2>
    Contact(T1&& name, T2&& num, T1&& addr, T1&& mail)
        :m_name{ std::forward<T1>(name) }, m_number{ num }, m_address{ std::forward<T1>(addr) }, m_mail{ std::forward<T2>(mail) }
    {
        std::cout << "template Contact constructor" << std::endl;
    }
};

template<typename T1, typename T2>
Employee* createObject(T1&& a, T2&& b, T2&& c)
{
    return new Employee{ std::forward<T1>(a), b, c };
}

I had tried a function for creating an instance for employee class. But i dont know how to do for both the classes

>Solution :

[…] I don’t know what to do for both classes?

Your createObject() just needs to be modified in a way that

  • it can also take the type of class the object has to be created, and
  • variadic template arguments for its parameters.

Something like:

template<typename T, typename... Args>
T* createObject(Args&&... args)
{
   return new T{ std::forward<Args>(args)... };
}

Live demo


As a side note, it’s generally best to prefer smart pointers over manual memory management, except when using raw pointers with new/delete for learning purposes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading