I have a struct consisting of a string
and a time_point
, and I want it to exhibit behavior similar to std::time_point
in C++20 with minimal code, without explicitly defining all comparison operators.
How can I achieve this?
My code :
#include <iostream>
#include <chrono>
#include <string>
struct MyStruct {
std::string name;
std::chrono::system_clock::time_point time;
// Comparison operators
bool operator==(const MyStruct& other) const {
return time == other.time;
}
bool operator!=(const MyStruct& other) const {
return !(*this == other);
}
bool operator<(const MyStruct& other) const {
return time < other.time;
}
bool operator<=(const MyStruct& other) const {
return time <= other.time;
}
// Prefix increment operator
MyStruct& operator++() {
++time;
return *this;
}
// Postfix increment operator
MyStruct operator++(int) {
MyStruct temp = *this;
++(*this);
return temp;
}
// and so on...
};
Why not just make your struct a time_point?
struct MyStruct : public std::chrono::system_clock::time_point
{
std::string name;
};
Aside from that, there is really no shame in acknowledging that your MyStruct
merely has a time
member, and just perform the operations on that one directly. Whichever fits the actual context better: is your MyStruct
actually a time_point
with a name, or does it just tell us the birthday of some guy?