I have been given this task to do :Task Description
Currently, I have no clue on how to do it. Any help will be appreciated. There is soo many classes therefore all cannot be shown.
If you are able to show me how to do it would be much appreciated. If not, any resources where I can learn to be able to do it would be really helpful too. I am currently struggling on this section.
The Scene class:
Scene::Scene() {
std::string blankline(WIDTH, ' ');
for (int i = 0; i < HEIGHT; i++)
{
page_ += (blankline + "\n");
}
}
void Scene::addObject(std::shared_ptr<Shape> ptr) {
vectPage_.push_back(ptr);
}
void Scene::setDrawDepth(int depth) {
sceneDepth_ = depth;
}
std::ostream& operator<<(std::ostream& out, const Scene& s)
{
return out;
}
Stuff in constructor was done myself
Scene.h
class Scene {
public:
// Constructor
Scene();
// Add the pointer to the collection of pointers stored
void addObject(std::shared_ptr<Shape> ptr);
// Set the drawing depth to d
void setDrawDepth(int d);
// Constants specifying the size of the drawing area
static constexpr int WIDTH = 60;
static constexpr int HEIGHT = 20;
private:
std::string page_;
std::vector<std::shared_ptr<Shape>> vectPage_;
int sceneDepth_;
friend std::ostream& operator<<(std::ostream& out, const Scene& s);
};
Base Class.h
class Shape
{
public:
// Constructor specifying the depth of the object.
// If d is negative, throw a std::invalid_argument exception.
Shape(int d);
// Set depth of object to d. If d is negative, return false and
// do not update depth. Otherwise return true
virtual bool setDepth(int d);
// Return the depth of object
virtual int getDepth() const;
// Return the dimension of the object (0, 1 or 2)
virtual int dim() const = 0;
// Translate the object horizontally by x and vertically by y
virtual void translate(float x, float y) = 0;
// Rotate the object 90 degrees around its centre
virtual void rotate() = 0;
// Scale the object by a factor f relative to its centre.
// If f is zero or negative, throw a std::invalid-argument exception.
virtual void scale(float f) = 0;
// Return true if the object contains p and false otherwise.
// Depths are ignored for purpose of comparison
virtual bool contains(const Point &p) const = 0;
// the constant pi
static constexpr double PI = 3.1415926;
virtual ~Shape() = 0;
protected:
int d;
float getX() const;
float getY() const;
};
Related
I am writing a program that has different shape classes
There is a base shape class similar to the following:
class Shape
{
public:
Shape(int x, int y, int size, COLORREF colorRef);
~Shape();
bool operator == (const Shape&) const;
int x() const;
int y() const;
int size() const;
protected:
int xCoord;
int yCoord;
int shapeSize;
COLORREF color;
};
And then some derived classes similar to the following:
class Circle : public Shape
{
public:
Circle(int x, int y, int size, COLORREF colorRef) : Shape(x, y, size, colorRef)
{
this->radius = (double)shapeSize / 2;
this->xCenter = (double)xCoord + radius;
this->yCenter = (double)yCoord - radius;
}
~Circle() {}
private:
double radius;
double xCenter;
double yCenter;
};
class Square : public Shape
{
public:
Square(int x, int y, int size, COLORREF colorRef) : Shape(x, y, size, colorRef) {}
~Square() {}
};
class Triangle : public Shape
{
public:
Triangle(int x, int y, int size, COLORREF colorRef) : Shape(x, y, size, colorRef) {}
~Triangle() {}
};
I would like to overload the == operator in the shape class so that I can determine if 2 shapes are identical. If I could assume both shapes being compared were of the same class then I know it would be fairly straight forward, but how do I go about testing whether 2 objects of the different derived classes are equal? For example, how do I determine that Triangle t != Circle c?
You have to determine which function to call based on type of two objects. This pattern in C++ is called double-dispatch (or Visitor pattern).
The most common implementation assumes that all derived classes (shapes in your example) are known - so you can list them in base class:
class Circle;
class Rectangle;
// all shapes here
class Shape {
public:
virtual ~Shape() = default; // good habit is to add virtual destructor to all polymorphic classes (those with virtual methods)
bool operator == (const Shape& other) const {
return equalTo(other);
}
virtual bool equalTo(const Shape& other) const = 0;
virtual bool doEqualTo(const Circle& other) const { return false; }
virtual bool doEqualTo(const Rectangle& other) const { return false; }
// etc.. for all other shapes
};
class Circle : public Shape {
// ...
protected:
virtual bool equalTo(const Shape& other) const
{
return other.doEqualTo(*this); // call doEqualTo(Circle) - first virtual dispatch
}
virtual bool doEqualTo(const Circle& other) const
{
return other.center == center && other.radius == radius; // second virtual dispatch
}
};
As you can see - to perform action - you have to call 2 virtual functions (so double-dispatch)
Ok, here's an idea for using the curious recurring template pattern to make implementing derived classes easier while allowing the == operator to work as expected. This maybe overkill, but it should work for your scenario.
Start by filling out your base Shape class. Added to your basic definition is an implementation of operator== that invokes a helper called CompareTypesAndDimensions. The function calls into two virtual methods, TypeCompare and Compare.
class Shape
{
public:
Shape(int x, int y, int size, COLORREF colorRef) : xCoord(x), yCoord(y), shapeSize(size), color(colorRef) {}
virtual ~Shape() {}; // need at least one virtual member for dynamic_cast
int x() const { return xCoord; }
int y() const { return yCoord; }
int size() const { return shapeSize; }
COLORREF col() const { return color; };
bool operator == (const Shape& other) const
{
return CompareTypesAndDimensions(other);
}
bool BaseShapeCompare(const Shape& other) const
{
return ((other.xCoord == xCoord) && (other.yCoord == yCoord) && (other.shapeSize == shapeSize) && (other.color == color));
}
virtual bool TypeCompare(const Shape& other) const = 0;
virtual bool Compare(const Shape& other) const = 0;
bool CompareTypesAndDimensions(const Shape& other) const
{
// make sure the types checks are reciprocals
// we don't accidently compare a "Square" with a "Rectangle" if they inherit from each other
if (TypeCompare(other))
{
return Compare(other);
}
return false;
}
protected:
int xCoord;
int yCoord;
int shapeSize;
COLORREF color;
};
The idea being with the above is that Circle, Triangle, and Square could just implement their own version of TypeCompare and Compare and be done with it. But wait! What if we could save some typing by having a template base class do some work for us - especially for validating that both compared instances are of the same type. And not having to a stock Compare function for the simpler types such as Square and Triangle.
Let's introduce a template class that inherits from Shape. This class, ShapeComparable provides the implementations for Compare and TypeCompare. The only thing it needs the concrete class below it to deal with is a method to handle comparing its own methods.
template <typename T>
class ShapeComparable : public Shape
{
public:
ShapeComparable(int x, int y, int size, COLORREF colorRef) : Shape(x, y,size,colorRef)
{}
bool TypeCompare(const Shape& other) const override
{
auto pOtherCastToDerived = dynamic_cast<const T*>(&other);
return (pOtherCastToDerived != nullptr);
}
bool Compare(const Shape& other) const override
{
if (BaseShapeCompare(other))
{
auto pOtherCastToDerived = dynamic_cast<const T*>(&other);
if (pOtherCastToDerived)
{
return this->CompareDerived(*pOtherCastToDerived);
}
}
return false;
}
// derived classes that don't have members to compare will just inherit this member
virtual bool CompareDerived(const T& other) const
{
return true;
}
};
The magic with the above is that TypeCompare utilizes a dynamic_cast to validate if the two instances being compared are of the same type. If you try to compare a Triangle to a Circle, the dynamic cast fails. Hence, operator== will return false.
Now let's see what the rest of the classes look like. Start with Circle, it inherits from ShapeComparable and provides an implementation for CompareDerived.
class Circle : public ShapeComparable<Circle>
{
public:
Circle(int x, int y, int size, COLORREF colorRef) : ShapeComparable(x,y,size,colorRef)
{
this->radius = (double)shapeSize / 2;
this->xCenter = (double)xCoord + radius;
this->yCenter = (double)yCoord - radius;
}
bool CompareDerived(const Circle& other) const
{
// BaseCompare has already been invoked by the time this method is invoked.
return ((other.radius == radius) && (other.xCenter == xCenter) && (other.yCenter == yCenter));
}
private:
double radius;
double xCenter;
double yCenter;
};
But Triangle and Square are as simple as it gets.
class Triangle : public ShapeComparable<Triangle>
{
public:
Triangle(int x, int y, int size, COLORREF colorRef) : ShapeComparable(x, y, size, colorRef) {}
};
class Square : public ShapeComparable<Square>
{
Square(int x, int y, int size, COLORREF colorRef) : ShapeComparable(x, y, size, colorRef) {}
};
And if you ever need to introduce a new property to Triangle and Square, you just need to provide a CompareDerived method.
The above works with the assumption is that you wouldn't have additional shapes derived from another concrete shape class. Otherwise, the CompareType function won't be reciprocal when comparing a Square to a Rhombus.
If I have two classes: one is Point and the second is Square, Point has member data: x and y those are "private" to represent the coordinates of the point.
The class Square and similar ones implement the "has-a" relationship; so for example Square has four Points. For some reason Point grants access to its private data through "friendship"; but only to a member function called print of the containing classes.
The problem:
The class Point needs to see the definition of the classes like Square so that it declares their print member as a friend.
Square needs to see the definition of class Point so that it can declare instances of it as its members.
Using forward-declaration won't solve the issue because the fact that it is still "incomplete type". So how it could be solved?
class Square;
class Point{
public:
using pos = int;
Point() = default;
Point(pos, pos);
pos getX()const{ return x_; }
pos getY()const{ return y_; }
void setX(pos x){ x_ = x; }
void setY(pos y){ y_ = y; }
private:
pos x_{};
pos y_{};
// friend void Square::print()const; // the problem here. Square is still incomplete type
// friend class Square; // we don't want this solution
};
inline Point::Point(pos x, pos y) :
x_{ x },
y_{ y }{
}
class Square{
public:
Square(const Point&, const Point&, const Point&, const Point&);
Point getPtA()const{ return ptA_; }
Point getPtB()const{ return ptB_; }
Point getPtC()const{ return ptC_; }
Point getPtD()const{ return ptD_; }
void setPtA(const Point& ptA){ ptA_ = ptA; }
void setPtB(const Point& ptB){ ptB_ = ptB; }
void setPtC(const Point& ptC){ ptC_ = ptC; }
void setPtD(const Point& ptD){ ptD_ = ptD; }
void print()const;
private:
Point ptA_, ptB_, ptC_, ptD_;
};
Square::Square(const Point& ptA, const Point& ptB, const Point& ptC, const Point& ptD) :
ptA_{ ptA }, ptB_{ ptB },
ptC_{ ptC }, ptD_{ ptD }{
}
void Square::print()const{
using pos = Point::pos;
for(pos i{ptA_.x_}; i != ptB_.x_; ++i){
for(pos j{ptA_.y_}; j != ptC_.y_; ++j)
std::cout << "*";
std::cout << std::endl;
}
}
I have a low-level embedded application, where I have some relatively large const, global, static arrays (lookup tables and such). The compiler (or linker) stores them in Flash memory rather than in RAM, since they are const.
Now, I have a class that needs to be initialized with one such array. It will use the data from that array throughout the lifetime of the class object.
My question is: how can I safely pass a pointer to this global, static array to the object, while preventing mistakenly passing an array with a short lifetime rather than a static one?
For example, consider the naive implementation that doesn't protect from incorrect initialization:
class Interpolator
{
public:
Interpolator(const float table[], int size);
float interpolate(float x); // uses 'table' data member
private:
const float* table;
int size;
};
Interpolator::Interpolator(const float table[], int size) :
table(table), size(size)
{
}
const float table1[] = {1.0, 2.0, 42.0 /* a few thousand more */ };
void main()
{
Interpolator interpolator1(table1, sizeof(table1) / sizeof(float));
float x = interpolator1.interpolate(17.0); // OK
float* table2 = new float[1024];
// ... calculate and fill in values in table2 ...
Interpolator interpolator2(table2, 1024); // how to prevent this usage?
delete[] table2; // incorrectly assume the object created a copy for itself and the delete is safe...
float y = interpolator2.interpolate(17.0); // ERROR, undefined behavior
}
How do I prevent the second instantiation in the example? perhaps through constexpr somehow, or some clever usage of templates...?
Notes:
I realize that the problem here is that my class doesn't conform to RAII. However, under the constraints explained above (use a large static array from Flash memory), I don't see how I can make it conform to RAII.
Copying the data from the static array to a local data member in the object is out of the question - a single array may literally be larger than my whole RAM, which is only tens of kB in size.
I will have multiple instances of the class, multiple static data tables, and several instances of the class may be initialized with the same static data table.
Any idea for a design pattern that enforces safety here?
thanks!
The address of a variable is a constant expression. This means we can use the address of the table as a template argument.
In this way we can build a specific template class for each interpolation table that exists, and no others.
This removes the possibility of creating an interpolator which points to a transient table.
It also has the advantage of requiring less storage since it does not need to maintain pointers to the data.
example:
#include <cstddef>
template<const float* const Table, std::size_t Size>
struct InterpolatorImpl
{
public:
float interpolate(float x)
{
// use Table and Size here as constant expressions
// or write in terms of begin() and end()
return 0;
}
constexpr std::size_t size() const
{
return Size;
}
constexpr const float* begin() const
{
return Table;
}
constexpr const float* end() const
{
return begin() + size();
}
};
const float table1[] = {1.0, 2.0, 42.0 /* a few thousand more */ };
using Interpolator1 = InterpolatorImpl<table1, sizeof(table1) / sizeof(float)>;
const float table2[] = {1.0, 3.0, 5.0 /* a few thousand more */ };
using Interpolator2 = InterpolatorImpl<table2, sizeof(table2) / sizeof(float)>;
int main()
{
Interpolator1 interpolator1;
float x = interpolator1.interpolate(17.0); // OK
float y = Interpolator2().interpolate(21);
}
But what if there were cases where we wanted to conditionally interpolate against one or another table?
In this case we could make the InterpolatorImpl polymorphic, deriving from a common base. We could then provide the common base with a means of performing interpolation based on table details acquired through a private virtual function.
#include <cstddef>
struct Interpolator
{
float interpolate(float x) const
{
return interpolate(getDetails(), x);
}
protected:
struct Details
{
const float* first;
std::size_t length;
};
private:
virtual Details getDetails() const = 0;
static float interpolate(Details details, float x)
{
// do interpolation here
auto begin = details.first;
auto size = details.length;
// ...
return 0;
}
};
template<const float* const Table, std::size_t Size>
struct InterpolatorImpl : Interpolator
{
public:
constexpr std::size_t size() const
{
return Size;
}
constexpr const float* begin() const
{
return Table;
}
constexpr const float* end() const
{
return begin() + size();
}
private:
virtual Details getDetails() const override
{
return { Table, Size };
}
friend auto poly(InterpolatorImpl const& i) -> Interpolator const&
{
return i;
}
};
const float table1[] = {1.0, 2.0, 42.0 /* a few thousand more */ };
using Interpolator1 = InterpolatorImpl<table1, sizeof(table1) / sizeof(float)>;
const float table2[] = {1.0, 3.0, 5.0 /* a few thousand more */ };
using Interpolator2 = InterpolatorImpl<table2, sizeof(table2) / sizeof(float)>;
float doInterpolation(Interpolator const& interp, float x)
{
return interp.interpolate(x);
}
bool choice();
int main()
{
Interpolator1 interpolator1;
Interpolator2 interpolator2;
float x = doInterpolation(choice() ? poly(interpolator1) : poly(interpolator2) , 17.0); // OK
}
But what if my compiler is a little old and does not treat the address of a variable as a constant expression?
Then we need a little hand-rolling for each interpolator:
#include <cstddef>
#include <type_traits>
struct Interpolator
{
float interpolate(float x) const
{
return interpolate(getDetails(), x);
}
protected:
struct Details
{
const float* first;
std::size_t length;
};
private:
virtual Details getDetails() const = 0;
static float interpolate(Details details, float x)
{
// do interpolation here
auto begin = details.first;
auto size = details.length;
// ...
return 0;
}
friend Interpolator const& poly(Interpolator const& self) { return self; }
};
const float table1[] = {1.0, 2.0, 42.0 /* a few thousand more */ };
struct Interpolator1 : Interpolator
{
virtual Details getDetails() const override
{
return {
table1,
std::extent<decltype(table1)>::value
};
}
};
const float table2[] = {1.0, 3.0, 5.0 /* a few thousand more */ };
struct Interpolator2 : Interpolator
{
virtual Details getDetails() const override
{
return {
table2,
std::extent<decltype(table2)>::value
};
}
};
float doInterpolation(Interpolator const& interp, float x)
{
return interp.interpolate(x);
}
bool choice();
int main()
{
Interpolator1 interpolator1;
Interpolator2 interpolator2;
float x = doInterpolation(choice() ? poly(interpolator1) : poly(interpolator2) , 17.0); // OK
}
https://godbolt.org/z/6m2BM8
I am receiving the "Debug error" CRT detected that the application wrote to memory after end of heap. But I don't understand why and can't find any similar examples.
The full code is...
Although I think it may just be a problem with main.
#include <iostream>
#include <cmath>
#include <array>
using namespace std;
// Declare global consts
const double pi = 3.1415926583;
// Base class Shape
class Shape{
protected:
double *sides;
public:
Shape(const int n){ //parameterized for n dimensional shape
sides = new double[n];
}
// need virtual destructor
virtual ~Shape(){
delete[] sides;
}
virtual double area() const = 0; // pure virtual function for area
virtual double volume() const = 0; // pure virtual function for volume
};
//////////////////////////////////////////////////////////
//Derived classes for 2D and 3D Shapes
class Shape2D : public Shape{ // inherit shape
protected:
int n = 2; //n denotes the number of dimensions
public:
// default constructor
Shape2D() :Shape(n){}
// param constructor
Shape2D(const double side1, const double side2) :Shape(n){
sides[0] = side1; sides[1] = side2;
}
virtual ~Shape2D(){} //virtual destructor
double volume() const { cout << "trying to calculate volume of 2d shape..." << endl; return 0; };
};
/////////////////////////////////////////////////////////////////////
//2D shapes
class Rectangle : public Shape2D{
public:
// constructors
Rectangle() :Shape2D() {}
Rectangle(const double side1, const double side2) :Shape2D(side1, side2){}
~Rectangle(){}
double area() const { return (sides[0] * sides[1]); }
};
int main(){
Shape **ShapePointer = new Shape*[2];
ShapePointer[0] = new Rectangle(2, 5);
ShapePointer[1] = new Rectangle(1, 3);
// clean up
delete ShapePointer[0];
delete ShapePointer[1];
delete[] ShapePointer;
system("pause");
return 0;
}
Danger!!!
protected:
int n = 2; //n denotes the number of dimensions
public:
// default constructor
Shape2D() :Shape(n){}
n is undefined when you initialize Shape(n)
Same problem with
Shape2D(const double side1, const double side2) :Shape(n)
If you can, define n as static const (or static constexpr, because you tagged C++11)
protected:
static constexpr int n = 2; //n denotes the number of dimensions
Otherwise you should define a static const/constexpr variable (say nDef), with value 2, and initialize both n and Shape() with this constant.
Anyway, take in count that, now, Shape (a base class for Shape2D) is initialized before n, that is a member of the class.
the problem is the following two lines of the code:
int n = 2; //n denotes the number of dimensions
Shape2D(const double side1, const double side2) :Shape(n){ ... }
The problem is the Shape() gets executed before the n is initialized. See constructors-called-before-initializing-variables for details.
To solution to this would be to create a the following methods in the Shape class
protected:
void InitializeBuffer(const int n)
{
sides = new double[n]
}
and instead of initialize the sides in the parent constructor, call this InitializeBuffer with in the constructor of the Shape2D class
Shape2D(const double side1, const double side2) :Shape()
{
InitializeBuffer (n);
sides[0] = side1; sides[1] = side2;
}
I feel like this question must have been asked before but I couldn't find an answer from poking around on google. If it has please direct me to a link and I will remove this post.
Consider this minimal example that represents a larger problem I have. Say I created a simple "Point" and "Printer" class like so:
class Point {
public:
double x, y;
Point() {x = y = 0;}
Point(double x, double y) {
this->x = x; this->y = y;
}
};
template<typename T>
class Printer {
public:
T* mData;
int mSize;
// Constructor
Printer(std::vector<T> &input) {
mData = &input[0];
mSize = input.size();
}
// Simple Print function
void Print() {
printf(" - Showing %d items\n", mSize);
for (int i = 0; i < mSize; i++) {
const T &item = mData[i];
printf(" - Item %d: (%lf, %lf)\n", i, item.x, item.y);
}
}
};
I could use the printer class like this:
std::vector<Point> points; // fill the vector, and then...
Printer<Point> pointsPrinter(points); pointsPrinter.Print();
Now say someone else comes along and wants to use the Printer class with there own "Point" class declared like so:
class Pnt {
public:
double mX, mY;
// other stuff
};
If they try to do this:
vector<Pnt> pnts; // Fill the pnts, and then...
Printer<Pnt> pntsPrinter(pnts);
pntsPrinter.Print(); // COMPILE ERROR HERE!
Obviously this will fail because Pnt has no x or y members. Does there exist a way I can rewrite the Printer class to work with all generic user types? What I DONT want to do is copy a Pnt vector into a Points vector.
EDIT:
The only way I can think to make this work would be to pass in functions pointers. Something like this:
template<typename T>
class Printer {
public:
T* mData;
int mSize;
double* (*mXFunc) (T*);
double* (*mYFunc) (T*);
Printer(std::vector<T> &input,
double* (*xFunc) (T*),
double* (*yFunc) (T*))
{
mData = &input[0];
mSize = input.size();
mXFunc = xFunc;
mYFunc = yFunc;
}
void Print() {
printf(" - Showing %d items\n", mSize);
for (int i = 0; i < mSize; i++) {
T &item = mData[i];
printf(" - Item %d: (%lf, %lf)\n", i, *mXFunc(&item), *mYFunc(&item));
}
}
};
// Could then use it like so
inline double* getXPointVal(Point *point) {return &point->x;}
inline double* getYPointVal(Point *point) {return &point->y;}
inline double* getXPntVal(Pnt *point) {return &point->mX;}
inline double* getYPntVal(Pnt *point) {return &point->mY;}
Printer<Pnt> pntPrinter(pnts, getXPntVal, getYPntVal);
Printer<Point> pointsPrinter(points, getXPointVal, getYPointVal);
pntPrinter.Print();
pointsPrinter.Print();
The problem with this is that it looks ugly and also possibly introduces the function call overhead. But I guess the function call overhead would get compiled away? I was hoping a more elegant solution existed...
If you choose cout instead of printf to write your output, you can allow all printable types to define an overload for the << operator and use that generically inside Printer::print(). An overload could look like this:
std::ostream& operator<<(std::ostream &out, Point& p){
out << "Point(" << p.x << ", " << p.y << ")";
return out;
}
On a side note, I advise against storing a pointer to a vector's internal storage and size member. If the vector needs to reallocate, your pointer will be left dangling and invalid. Instead, you should pass the vector temporarily as a reference or keep a const reference.
You could define free (non-member) functions for each Point class you want to use. The advantage of this is that free functions can be defined later, without making changes to existing classes.
Example:
namespace A {
class Point {
public:
Point (int x, int y) : x_(x), y_(y) {}
int getX () const { return x_; }
int getY () const { return y_; }
private:
int x_, y_;
};
// in addition, we provide free functions
int getX (Point const & p) { return p.getX(); }
int getY (Point const & p) { return p.getY(); }
}
namespace B {
class Pnt {
public:
Pnt (int x, int y) : x_(x), y_(y) {}
int get_x () const { return x_; }
int get_y () const { return y_; }
private:
int x_, y_;
};
// Pnt does not have free functions, and suppose we
// do not want to add anything in namespace B
}
namespace PointHelpers {
// free functions for Pnt
int getX (Pnt const & p) { return p.get_x (); }
int getY (Pnt const & p) { return p.get_y (); }
}
// now we can write
template <class PointTy>
void printPoint (PointTy const & p) {
using PointHelpers::getX;
using PointHelpers::getY;
std::cout << getX (p) << "/" << getY (p) << std::endl;
}
A::Point p1 (2,3);
B::Pnt p2 (4,5);
printPoint (p1);
printPoint (p2);
If the free functions live in the same namespace as the corresponding class, they will be found by argument-dependent name lookup. If you do not want to add anything in that namespace, create a helper namespace and add the free functions there. Then bring them into scope by using declarations.
This approach is similar to what the STL does for begin and end, for instance.
Don't expect from the templates to know which members of given class/structure corresponds to your x and y...
If you want to create generic solution you could tell your printer function how to interpret given object as your Point class using e.g. lambda expression (c++11 solution):
#include <iostream>
class Point {
public:
double x, y;
Point() {x = y = 0;}
Point(double x, double y) {
this->x = x; this->y = y;
}
};
class Pnt {
public:
double mX, mY;
// other stuff
};
template <class P, class L>
void Print(const P &p, L l) {
Print(l(p));
}
void Print(const Point &p) {
std::cout << p.x << ", " << p.y << std::endl;
}
int main() {
Print(Point(1, 2));
Print(Pnt{4, 5}, [](const Pnt &p) -> Point {return Point(p.mX, p.mY);});
}