Menu

Generic Factory Method

Anonymous

Generic factory method with factory method map

Exmaple:

#include "FactoryMethod.hpp"
#include <iostream>

namespace pu = ProjectUtilites;

struct Field {
    Field(){ std::cout << "Filed:"; }
};

struct GoodField : Field {
    GoodField(){ std::cout << "Good\n"; }
};

struct BadField : Field {
    BadField(){ std::cout << "Bad\n"; }
};

int main(){
    pu::FactoryMethodMap< Field >::add< GoodField >( "good" ); // adding with default create function using new    
    pu::FactoryMethodMap< Field >::add( "bad", []() -> Field * { return new BadField; } );
    pu::FactoryMethodMap< Field >::create( "good" );
    pu::FactoryMethodMap< Field >::create( "bad" );
    pu::FactoryMethodMap< Field >::create( "good" );
    return 0;
}

Print in console:
Filed:Good
Filed:Bad
Filed:Good


MongoDB Logo MongoDB