time_point extension to a struct holding another member

77 Views Asked by At

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...
};
2

There are 2 best solutions below

3
Christian Stieber On BEST ANSWER

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?

1
Eugene On

In C++20, instead of 6 comparison operators, you only need to define operator== and operator<=> (aka spaceship operator):

struct MyStruct {
    std::string name;
    std::chrono::system_clock::time_point time;

    // Comparison operators
    bool operator==(const MyStruct& other) const {
        return time == other.time;
    }
    auto operator<=>(const MyStruct& other) const {
        return time <=> other.time;
    }

All other comparison operators (<,>,<=,>=,!=) will be generated from these two.

However, there is no C++20-specific magic for other operators (operator++ etc.)