Skip to content

Instantly share code, notes, and snippets.

@hallfox
Last active January 27, 2018 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hallfox/e08838446da787b2355b4ea1524e61bd to your computer and use it in GitHub Desktop.
Save hallfox/e08838446da787b2355b4ea1524e61bd to your computer and use it in GitHub Desktop.
How curious...
#include "Circle.h"
const double Circle::PI = 3.14;
Circle::Circle(double radius):
radius_(radius) {}
double Circle::area() const {
return _radius * _radius * PI;
}
#include "Shape.h"
class Circle: public Shape<Circle> {
public:
Circle(double radius);
double area() const;
private:
double radius_;
static const double PI;
};
#include "Rectangle.h"
#include "Circle.h"
#include "Shape.h"
#include <iostream>
int main(int argv, const char* argv[]) {
//Shape s1; // Can't be created because pure virtual, compile error
Rectangle r1;
// Compiler directly inserts call to Rectangle::area
std::cout << r1.area() << std::endl;
Shape<Rectangle>& s2 = r1; // Ok
// Call Shape<Rectangle>::area()
std::cout << s2.area() << std::endl;
return 0;
}
#include "Rectangle.h"
Rectangle::Rectangle(double length, double width):
length_(length),
width_(width) {}
double Rectangle::area() const {
return length_ * width_;
}
#include "Shape.h"
class Rectangle: public Shape<Rectangle> {
public:
Rectangle(double length, double width);
double area() const;
private:
double length_;
double width_;
};
template <typename Derived>
class Shape {
public:
// I disallow the ability to create a Shape, it would be meaningless
Shape() = delete;
double area() const;
};
template <typename Derived>
double Shape<Derived>::area() const {
return static_cast<Derived*>(this)->area();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment