Re: static polymorphism and Factory Pattern
<alexander.stippler@uni-ulm.de> schrieb im Newsbeitrag
news:1153911418.344276.274650@m79g2000cwm.googlegroups.com...
Hello,
I need on the one hand static polymorphism for efficiency concerns,
But I also want the following: Which specific problem I have to
instantiate is given by some external run-time value, let's say by a
string.
If you could put the creation and the handling of the problem into 1
function it could be done like this:
(But it is no longer evident what the Baseclass Problem<T> is for)
#include <map>
#include <string>
template <typename P>
class Problem
{
public:
const P &
problem() const { return static_cast<const P &>(*this); }
P &
problem() { return static_cast<P &>(*this); }
void
method1() { this->problem().method1(); }
// .... other methods
};
template <typename T>
class SpecificProblem
: public Problem<SpecificProblem<T> >
{
public:
void method1() {}
};
typedef void (*CreateAndSolveFunction)();
template<typename P> void Solve(Problem<P>& trouble)
{
trouble.method1();
}
template<typename ConcreteTrouble> void DoCreateAndSolve()
{
SpecificProblem<ConcreteTrouble> concreteTrouble;
Solve(concreteTrouble);
}
typedef std::map<std::string, CreateAndSolveFunction> SolvableProblems;
SolvableProblems InitSolvableProblems()
{
SolvableProblems result;
result[std::string("int")]=&DoCreateAndSolve<int>;
return result;
}
void CreateAndSolve(std::string const& problemId)
{
static const SolvableProblems solvableProblems = InitSolvableProblems();
SolvableProblems::const_iterator where =
solvableProblems.find(problemId);
if(where != solvableProblems.end())
(*where->second)();
}
int main()
{
CreateAndSolve("int");
}
Regards,
Arne