在chrono中获取时间类型的名称

Nik*_*iou 5 c++ c++11 c++-chrono c++14

假设我有一个测量类的时间,可以通过这样的持续时间类型进行参数化

template<typename TimeT = std::chrono::milliseconds>
struct measure
{ /* implementation */ };
Run Code Online (Sandbox Code Playgroud)

我想要的是能够打印出来的TimeT.我倾向于实现这样的静态成员函数:

static string TimeType() const; 
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 我应该添加会员吗?这不应该是静态的吗?
  2. 如何实施这个体制?我应该使用依赖于实现的非编译时typeinfo / name组合(在这种情况下我必须删除constexpr上面的内容)或者我应该选择创建几个特殊化,这些特化会在每种类型时返回正确的字符串吗?
  3. 是否有更标准/惯用的方式来获取时间类型的名称?

How*_*ant 11

欢迎您使用我的<chrono_io>图书馆.它由单个标题组成,"chrono_io.h"在文档中链接到该标题.使用示例如下:

#include "chrono_io.h"
#include <iostream>

template<typename TimeT = std::chrono::milliseconds>
struct measure
{
    TimeT value;

    friend
    std::ostream&
    operator<< (std::ostream& os, const measure& m)
    {
        using namespace date;
        return os << m.value;
    }
};

int
main()
{
    using namespace std::chrono;
    measure<> m1 = {30ms};
    std::cout << m1 << '\n';
    measure<duration<int, std::ratio<1, 60>>> m2 = {duration<int, std::ratio<1, 60>>{45}};
    std::cout << m2 << '\n';
}
Run Code Online (Sandbox Code Playgroud)

哪个输出:

30ms
45[1/60]s
Run Code Online (Sandbox Code Playgroud)

  • 所以有时候很棒.我的意思是你发一个问题,那个建立整个事情的人回答......欢呼H! (5认同)

Nik*_*iou 6

一种方法是专注于时间类型; 这种方式的不可移动性typeid.name()是一个因素:

/// get the name of the chrono time type
template<typename T> string time_type()                  { return "unknown";      }
template<> string time_type<std::chrono::nanoseconds >() { return "nanoseconds";  }
template<> string time_type<std::chrono::microseconds>() { return "microseconds"; }
template<> string time_type<std::chrono::milliseconds>() { return "milliseconds"; }
template<> string time_type<std::chrono::seconds     >() { return "seconds";      }
template<> string time_type<std::chrono::minutes     >() { return "minutes";      }
template<> string time_type<std::chrono::hours       >() { return "hours";        }
Run Code Online (Sandbox Code Playgroud)

这个q并没有引起太多关注.我发布了一个答案作为代码质量比较的最小基础

当然,这里的困难案例是在编译时获得这些信息,这需要编译时字符串 n'的东西

上面的另一个版本是

template<class> struct time_type          { constexpr static char const *name = "unknown";      };
template<> struct time_type<nanoseconds > { constexpr static char const *name = "nanoseconds";  };
template<> struct time_type<microseconds> { constexpr static char const *name = "microseconds"; };
template<> struct time_type<milliseconds> { constexpr static char const *name = "milliseconds"; };
template<> struct time_type<seconds     > { constexpr static char const *name = "seconds";      };
template<> struct time_type<minutes     > { constexpr static char const *name = "minutes";      };
template<> struct time_type<hours       > { constexpr static char const *name = "hours";        };
Run Code Online (Sandbox Code Playgroud)