Factory.h
1//-*-C++-*-
2/***************************************************************************
3 *
4 * Copyright (C) 2004 by Willem van Straten
5 * Licensed under the Academic Free License version 2.1
6 *
7 ***************************************************************************/
8
9// psrchive/Util/units/Factory.h
10
11#ifndef __MEAL_Factory_H
12#define __MEAL_Factory_H
13
14#include "Functor.h"
15#include "stringtok.h"
16
17#include <fstream>
18
19namespace Factory {
20
21 template< class T >
22 T* load (const std::string& filename,
23 Functor< T*(std::string) >& constructor,
24 bool verbose = false)
25 {
26 std::ifstream input (filename.c_str());
27 if (!input)
28 throw Error (FailedSys, "Factory::load", "ifstream (" + filename + ")");
29
30 std::string line;
31
32 T* instance = 0;
33
34 while (input)
35 {
36 std::getline (input, line);
37 line = stringtok (line, "#\n", false); // get rid of comments
38
39 if (!line.length())
40 continue;
41
42 if (!instance)
43 {
44 // the first key loaded should be the name of the instance
45 std::string key = stringtok (line, WHITESPACE);
46
47 if (verbose)
48 std::cerr << "Factory::load construct new " << key << std::endl;
49
50 instance = constructor (key);
51
52 if (!line.length())
53 continue;
54 }
55
56 if (verbose)
57 std::cerr << "Factory::load parse line '" << line << "'" << std::endl;
58
59 instance->parse (line);
60
61 }
62
63 if (!instance)
64 throw Error (InvalidParam, "Factory::load", "nothing constructed from '" + filename + "'");
65
66 return instance;
67
68 }
69
70}
71
72#endif
73

Generated using doxygen 1.14.0