Thursday, November 14, 2013

policy class

#include <iostream>

using namespace std;

template<class T>
struct Creator_1
{
    static T* create(){
        T* node = new T();
        *node = 40;
        return node;
    };
};

template<class T>
struct Creator_2
{
   // you don't want to do this way.  Doing so for demo purpose.
    static T* create(){
        T a=100;
        return &a;
    };
};

// Way 1 to declare it :

template <class CreationPolicy>
class CreatorManger: public CreationPolicy
{
};

// Way 2 to declare:  template template class.
template <template <class T> class CreationPolicy>
class CreatorManger_2: public CreationPolicy<int>
{
};

int main()
{
    // Way 1 to use it : expect any type as template argument.

    CreatorManger<Creator_1<int> > manager;
    CreatorManger<Creator_2<int> > manager2;

    int* ip1 = manager.CreatorManger::create();
    int* ip2 = manager2.CreatorManger::create();

    cout << *ip1 << endl;
    cout << *ip2 << endl;


    // Way 2 to use it : expect a template class as template argument

    CreatorManger_2<Creator_1> manager3;
    CreatorManger_2<Creator_2> manager4;

    int* ip3 = manager3.CreatorManger_2::create();
    int* ip4 = manager4.CreatorManger_2::create();

    cout << *ip3 << endl;
    cout << *ip4 << endl;


    return 0;
}

No comments:

Post a Comment