inheritance - C++ virtual function override -



inheritance - C++ virtual function override -

i have class contains next virtual method:

struct point { template<typename t> virtual typename std::enable_if<std::is_base_of<point, t>::value, double>::type distto(t &other) const = 0; };

the above doesn't work because:

error: templates may not ‘virtual’

the plan specialize class making more specific instances of point2d, point3d. however, want function work types of same class. if point2d inherit class, method distto should take parameter of type point2d. how can accomplish this?

this had tried before did above:

virtual double distto(point& other) = 0;

but when override method in point2d class , seek replace parameter 1 of type point2d, run compiler errors.

thanks time

i think requirements create no sense static typed language such c++.

think how able utilize virtual function:

point2d p1, p2; point3d p3; point &p = p1; p.distto(p2); //ok? p.distto(p3); //error?

that not possible, because @ compile time compiler not know if p reference point2d or point3d, @ runtime.

you add together explicit cast , runtime assertion if wrong, think create little sense. do:

struct point { /*...*/ }; struct point2d : point { double distto(const point2d &other); }; struct point3d : point { double distto(const point3d &other); };

and not phone call distto using base of operations point references.

update: if know list homogeneous, don't know cardinality, can do:

struct point { virtual double distto(const point &other) =0; }; struct point2d : point { double distto(const point2d &other) { /*...*/ } virtual double distto(const point &other) { const point2d &other2 = static_cast<const point2d &>(other); homecoming distto(other2); } }; struct point3d : point { double distto(const point3d &other) { /*...*/ } virtual double distto(const point &other) { const point3d &other3 = static_cast<const point3d &>(other); homecoming distto(other3); } };

but beware! if phone call point::distto wrong object, result undefined!

c++ inheritance polymorphism abstract-class

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -