mercredi 18 avril 2018

Allow implicit casting for types with the same underlying structure

I've got several structures in my code which all have

  • one member with the same type, e.g. std::pair or cv::Point2d
  • different functions, e.g. getters/setters named differently in each struct

Example:

struct CartesianCoordinates {
    std::pair<double, double> xy;

    void x(double val) { xy.first = val; }
    void y(double val) { xy.second = val; }
    double x() const { return xy.first; }
    double y() const { return xy.second; }
};

struct GeographicCoordinates {
    std::pair<double, double> xy;

    void longtitude(double val) { xy.first = val; }
    void lattitude(double val) { xy.second = val; }
    double longtitude() const { return xy.first; }
    double lattitude() const { return xy.second; }
};

Now I want to be able to convert between those types implicitly, like this:

CartesianCoordinates returnCartesian()
{
    CartesianCoordinates c;
    c.x(5);
    c.y(-13);
    return c;
}

void getGeographicCoordinates(const GeographicCoordinates& c) {
    std::cout << c->longtitude() << '\n';
}

int main()
{
    getGeographicCoordinates(returnCartesian());
}

Is there any way to achieve this without

  • defining cast operators (I don't want to define those in every struct, 1:1),
  • providing base class for those structures (if I don't want to define any base class)?

In fact reinterpret_cast/pointers should work, but do any modern C++ mechanism exist that I am not aware of and that could help me to solve it with least structures implementation overhead, just using the fact that all structures have the same structure inside?

Aucun commentaire:

Enregistrer un commentaire