Skip to main content
1 of 2

Get or infer template type from inherited member

So I have an assignment from college where I have to apply multiple metaheuristics to different problems. I thought that I should make everything as modular and reusable as possible to reuse metaheuristics with different problems with as little change as possible.

I need this classes:

  • Solution
  • NeighbourOperator
  • ExplorationStrategy
  • Metaheuristic

My thoughts initially were that Metaheuristic would contain an ExplorationStrategy which would contain a NeighbourOperator. The strategy would receive a solution and return a neighbour based on its members. The exploration strategy and metaheuristc would have the solution class as a template.

My ideal main.cpp would look like:

SomeProblemSolution<int> solt = randomGeneratedSolution();
SomeNeighbourOperator op;
SomeExplorationStrategy<SomeProblemSolution> strat(op);
SomeMetaheuristic<SomeProblemSolution> mthr(strat);

mthr.apply(solt);

But this is what the code would look like:

SomeProblemSolution<int> solt = randomGeneratedSolution();
SomeNeighbourOperator<int> op;
SomeExplorationStrategy<SomeProblemSolution, int> strat(op);
SomeMetaheuristic<SomeProblemSolution, int> mthr(strat);

mthr.apply(solt);

Now every class that interacts with a solution requires a template.

template<class T>
class NeighOperator {
    public:
        virtual void applyOp(Solution<T> &, int) = 0;
....

template<class T, class S>
class NeighExplorator {
    protected:
        NeighOperator<S> *_neighOperator;

    public:
        virtual T exploreNg(T &sol) = 0;
....

So

Is there any design error by which I need the template type of the solution in every other class?

Is there anyway to make the program generic as to only use the template type (the one that represents the solution) in Solution and not in every place where there's a solution involved?

Am I doing something wrong with templates (should I somehow infer the type) or should I just friend the classes I need?

Any help is much appreciated.