vendredi 26 mars 2021

How the compiler infer types using strategy pattern (with overloaded() in struct or class)?

I am struggling to understand how this code even compile when passing a "callable" struct/class.

Referring to the main function below, I would expect the compiler to tell me that there is no matching constructor for Point3D (CallableI is not an instance of FuncType).

What I would be tempting to do is to create an algo member inside CallableI and constructs the point referring to it. But this solution is better on many aspect so I want to understand how it is working under the hood.

I have a base class Point3D :

template<typename T>
class Point3D
{
typedef std::function<T (const Point3D<T> &p1, const Point3D<T> &p2)> FuncType;
private:
    T x;
    T y;
    T z;
    FuncType algo;
public:
    Point3D(T x, T y, T z, FuncType algo) : x(x), y(y), z(z), algo(algo){}
    T First() const {return x;}
    T Second() const {return y;}
    T Third() const {return z;}
    
    T computeDistance(Point3D<T> &p2){
        return algo(*this, p2);
    }
};

I am using a struct CallableI to hold a particular function to be called overloading operator ().

struct CallableI
{
    CallableI(){};
    
    double operator() (const Point3D<double> &p1, const Point3D<double> &p2){
        double x1{p1.First()}; double x2{p2.First()};
        double y1{p1.Second()}; double y2{p2.Second()};
        return std::abs(x1 - x2) + std::abs(y1 - y2);
    }
};

And I am calling the suggested code with the main function below :

int main(int argc, char **argv) {
    
    CallableI myCallable;
    Point3D<double> p1(14.3, 12.3, 2.0, myCallable);
    return 0;

Aucun commentaire:

Enregistrer un commentaire