Created
December 14, 2011 05:01
-
-
Save juehan/1475335 to your computer and use it in GitHub Desktop.
generic factory function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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