Search code examples
c++classooptemplatesfunction-templates

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


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

I have two classes Employee and Contact and to create an instance for both classes by a single factory function: I have no clue how to do that!

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 tried a function for creating an instance for Employee class. But I do not know what to do for both 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.