Skip to content

Instantly share code, notes, and snippets.

@juehan
Created December 14, 2011 05:01
Show Gist options
  • Save juehan/1475335 to your computer and use it in GitHub Desktop.
Save juehan/1475335 to your computer and use it in GitHub Desktop.
generic factory function
#include <memory>
#include <string>
#include <iostream>
//Example class
class Dog
{
public:
explicit Dog(std::string& name) : m_name(name), m_age(1){}
explicit Dog(int age) : m_name("Happy"), m_age(age){}
const std::string& getName() const {return m_name;}
const int getAge() const { return m_age;}
private:
std::string m_name;
int m_age;
};
//Generic factory function
template<class T, class A>
std::unique_ptr<T> Create(A& a)
{
return std::unique_ptr<T>(new T(a));
}
//Application code
int main()
{
{
using namespace std;
string name("Merry");
unique_ptr<Dog> p1 = Create<Dog, string>(name);
cout<<"P1: name("<<p1->getName()<<"), age("<<p1->getAge()<<")"<<endl;
int age = 5;
unique_ptr<Dog> p2 = Create<Dog, int>(age);
cout<<"P2: name("<<p2->getName()<<"), age("<<p2->getAge()<<")"<<endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment