lundi 3 février 2020

Adapter design pattern with templates failed C++

I think the problem (segmentation fault) arises because solve() method wasn't override correctly (template parameters). I'm not sure how can someone write an adapter for Solver ---- Adapter --- Searcher if they have different template parameters.

-----In main()-------:

Matrix *matrix = matrixCreator.createFromFile(name);
    list<State<Point *> *> *path;
    vector<Point *> vec;
    //auto *solver = new Solver<list<State<Point *> *> *, Searchable<Point *> *>;
//  auto adapter = std::make_shared< Adapter<Point*, list<State<Point *>*> * >>();
    auto *adapter = new Adapter<Point*, list<State<Point*>*> *>;
    cout << "\ntest dfs\n" << endl;
    //std::shared_ptr<Searcher<Point *> > dfs = std::make_shared< DFS<Point *> >();
    auto * dfs = new DFS<Point *>;
    adapter->setSearcher(dfs); //No member named 'setSearcher' in 'Adapter<Point *, std::__cxx11::list<State<Point *> *, std::allocator<State<Point *> *> > *>'

    path = adapter->solve(matrix); // **SIGSEGV segmentation fault here** <--------------------

--------DFS.h----------:

template<class P>
    class DFS : public Searcher<P> {

public:
    list<State<P> *> * search(Searchable<P> *searchable) override {

---------- Searcher.h: --------

template<class P>
class Searcher {
public:
    //virtual S search(shared_ptr<P> problem);
//    Searcher();
    virtual list<State<P> *> * search(Searchable<P> *searchable) ;

---------- Adapter.h: ---------

#include "Solver.h"
#include "Searcher.h"
//Problem = Point*
template<class Problem, class Solution>
class Adapter : public Solver<Searchable<Problem>*,Solution> {

private:
    //std::shared_ptr<Searcher<Problem> > searcher;
    Searcher<Problem> * searcher;

public:
    //Adapter(Searcher<Problem, Solution>);
    Adapter();
    Solution solve(Searchable<Problem>* problem) override ;
    //void setSearcher(std::shared_ptr<Searcher<Problem>>);
    void setSearcher(Searcher<Problem> *);

};

template<class Problem, class Solution>
Solution Adapter<Problem, Solution>::solve(Searchable<Problem>* problem) {
    cout << "\nin solve\n" << endl;
    return searcher->search(problem);
}


template<class Problem,class Solution>
void Adapter<Problem,Solution>::setSearcher( Searcher<Problem> * searcher) {
    //void Adapter<Problem,Solution>::setSearcher( std::shared_ptr<Searcher<Problem>> searcher) {
        Adapter::searcher = searcher;
//    }
}

template<class Problem, class Solution>
Adapter<Problem, Solution>::Adapter() {
    this->searcher = nullptr ;
}

--------- Solver.h: ---------

template <class Problem, class Solution>
class Solver {

public:
    virtual Solution solve (Problem problem)=0;
    //virtual ~Solver(){}
};

Aucun commentaire:

Enregistrer un commentaire