OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

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

  • Thread starter Thread starter Muthuraj
  • Start date Start date
M

Muthuraj

Guest
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!

Code:
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!
Continue reading...
 
Top