简体   繁体   中英

Declaring an interface with methods which has parameters of classes implementing the interface

I would like to create an interface

Coordinate

with the method

double distanceTo(Coordinate *otherCoord);

but I want the classes that implement the interface to implement their respective versions of distanceTo .

If for example GeographicCoordinate implements Coordinate then it should be forced to implement the method

double distanceTo(GeographicCoordinate *otherCoord);

rather then

double distanceTo(Coordinate *otherCoord);

What would be the syntax in C++ to express this?

You need Curiously recurring template pattern (CRTP)

template<typename DerivedType>
class Coordinate{

    double distanceTo(DerivedType *otherCoord) = 0;

};

class GeographicCoordinate: public Coordinate<GeographicCoordinate>

This would however make each baseclass unique to the derived class, which might be too far great a cost for this ( cannot store in containers etc)

Alternatively you could do it so that just double distanceTo(Coordinate *otherCoord); would suffice, by making the relavent functions virtual, doing away with the need to do templates.

Whilst there are situations when this is indeed necesary, the typical way to solve this problem is to use virtual functions in the base-class.

So for example:

// Example of how to describe a coordinate position - could be many other ways. 
struct PosType { double x; double y };

class Coordinate
{
 public:
    double distanceTo(Coordinate *otherCoord)
    {
        PosType position = getPosition();
        PosType otherPos = otherCoord->getPosition();
        ... use position and otherpos to calculate distance. 
    }
    virtual PosType getPosition() = 0; 
};


class GeographicCoordinate
{
  public:
   PosType getPosition() { return pos; }    

  private: 
   PosType pos; 
}

class SomeOtherCoordinate
{
  public:
   PosType getPosition() 
   { 
      PosType myPos = ... // perform some calculation/transformation. 
      return myPos; 
   }    
}

This way, you can perform any coordinate to any other coordinate calculation, no matter what type it is.

Obviously, there may be situations when this solution DOESN'T work, but in general, I'd say it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM