You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让含std::time_point的结构体极简实现类C++20 std::time_point的行为?

简化实现方案

要让MyStruct表现出类似std::chrono::time_point的行为,同时减少冗余代码,你可以利用C++20的**三路比较运算符(<=>)**自动生成所有比较逻辑,同时将增量/减量等操作直接委托给内部的time成员。

核心优化点

  • 自动生成比较运算符:通过默认三路比较运算符,基于time成员实现所有比较(==、!=、<、<=、>、>=),无需手动定义每个运算符。
  • 委托增量/减量操作:直接复用std::chrono::time_point已实现的增量、减量和时长运算,无需重复编写逻辑。
  • 支持时长运算:添加operator+=和operator-=,让MyStruct能像time_point一样与std::chrono::duration交互。

简化后的代码

#include <iostream>
#include <chrono>
#include <string>

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

    // C++20 三路比较:自动生成所有比较运算符
    auto operator<=>(const MyStruct& other) const = default;

    // 前缀增量:委托给time成员
    MyStruct& operator++() {
        ++time;
        return *this;
    }

    // 后缀增量:复用前缀实现
    MyStruct operator++(int) {
        MyStruct temp = *this;
        ++(*this);
        return temp;
    }

    // 前缀减量
    MyStruct& operator--() {
        --time;
        return *this;
    }

    // 后缀减量
    MyStruct operator--(int) {
        MyStruct temp = *this;
        --(*this);
        return temp;
    }

    // 时长加法
    template<typename Rep, typename Period>
    MyStruct& operator+=(const std::chrono::duration<Rep, Period>& d) {
        time += d;
        return *this;
    }

    // 时长减法
    template<typename Rep, typename Period>
    MyStruct& operator-=(const std::chrono::duration<Rep, Period>& d) {
        time -= d;
        return *this;
    }
};

// 非成员时长加法(可选,模仿time_point的行为)
template<typename Rep, typename Period>
MyStruct operator+(MyStruct ms, const std::chrono::duration<Rep, Period>& d) {
    ms += d;
    return ms;
}

// 非成员时长减法(可选)
template<typename Rep, typename Period>
MyStruct operator-(MyStruct ms, const std::chrono::duration<Rep, Period>& d) {
    ms -= d;
    return ms;
}

说明

  1. 三路比较运算符:auto operator<=>(const MyStruct& other) const = default; 会让编译器基于成员的默认比较逻辑生成所有比较运算符。由于std::chrono::time_point已经支持<=>,编译器会自动使用time成员的比较结果作为整个MyStruct的比较依据。
  2. 操作委托:所有增量、减量和时长运算都直接调用time成员的对应方法,完全复用std::chrono::time_point的实现逻辑,避免重复造轮子。
  3. 模板化时长运算:使用模板支持任意std::chrono::duration类型,和time_point的行为保持一致。

内容的提问来源于stack exchange,提问作者Ted Zach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 22:55:19