dimanche 4 octobre 2015

Single struct adjusting methods to different data types

I have a four very similar structs (very simple to illustrate the problem) differing in type of the arguments

using state_type = std::vector<double>;

struct foo {
    double _x;
    double _y;

    foo (double x, double y) : _x{x}, _y{y} {}

    void operator() (const state_type &v, state_type &u) const {
       for (auto i=0; i<v.size(); i++)
          u[i] = x * v[i] + y * v[i];
    }
}

struct foo {
    state_type _x;
    double _y;

    foo (state_type x, double y) : _x{x}, _y{y} {}

    void operator() (const state_type &v, state_type &u) const {
       for (auto i=0; i<v.size(); i++)
          u[i] = x[i] * v[i] + y * v[i];
    }
}

struct foo {
    double _x;
    state_type _y;

    foo (double x, state_type y) : _x{x}, _y{y} {}

    void operator() (const state_type &v, state_type &u) const {
       for (auto i=0; i<v.size(); i++)
          u[i] = x * v[i] + y[i] * v[i];
    }
}

struct foo {
    state_type _x;
    state_type _y;

    foo (state_type x, state_type y) : _x{x}, _y{y} {}

    void operator() (const state_type &v, state_type &u) const {
       for (auto i=0; i<v.size(); i++)
          u[i] = x[i] * v[i] + y[i] * v[i];
    }
}

Is there a way to use just a single struct that automatically chooses the right one based on the type of the arguments?

Aucun commentaire:

Enregistrer un commentaire