| constexpr/constexpr-2.cpp - Examples of a literal type, struct Point - C++11. | Lecture 6 - slide 33 : 40 Program 5 |
// Illustrates a struct Point - a literal type - with constexpr member functions.
#include <iostream>
#include <string>
struct Point { // A literal type
double x, y;
constexpr double getx () {return x;}
constexpr double gety () {return y;}
constexpr Point move(double dx, double dy){return Point{x + dx, y + dy};}
};
// Points handled at compile-time - the last is an array of points:
constexpr Point origo {0,0};
constexpr Point p1 = origo.move(3.1, 4.2);
constexpr Point pa[] = {origo, p1, p1.move(0.9, -0.2)};
int main(){
using namespace std;
cout << "(" << origo.getx() << "," << origo.gety() << ")" << endl; // (0,0)
cout << "(" << p1.getx() << "," << p1.gety() << ")" << endl; // (3.1, 4.2)
for(auto p: pa)
cout << "(" << p.getx() << "," << p.gety() << ")" << endl; // (0,0) (3.1, 4.2) (4,4)
}