任何类型的C ++用户定义文字

时间:2016-11-14 15:00:02

标签: c++ c++17 user-defined-literals

目前,用户定义的文字接受一组有限的类型作为输入参数(参见here)。有没有计划接受任何类型作为输入参数,如果没有,为什么会这样?

例如,我可能希望能够以不同的格式(秒,毫秒等)获得std :: chrono :: duration,并且可以执行类似

的操作
constexpr double operator"" _s(std::chrono::nanosecond time)
{
   return std::chrono::duration_cast<std::chrono::duration<double, std::chrono::seconds::period>>(time).count();
}

constexpr long operator"" _us(std::chrono::nanoseconds time)
{
    return std::chrono::duration_cast<std::chrono::microseconds>(time).count();
}

// And so on ...

int main()
{
    auto t0 = std::chrono::high_resolution_clock::now();
    // do some stuff
    auto t1 = std::chrono::high_resolution_clock::now();

    std::cout << "Time in seconds : " << (t1 - t0)_s << "s\n";
    std::cout << "Time in microseconds : " << (t1 - t0)_us << "µs\n";

    return 0;
}

1 个答案:

答案 0 :(得分:0)

也许你可以使用辅助结构代替:

#include <chrono>
#include <iostream>

using namespace std::literals::chrono_literals;

template <class Duration>
struct dc {
    using rep = typename Duration::rep;
    const std::chrono::nanoseconds time;
    constexpr dc(std::chrono::nanoseconds time):time(time) { }
    constexpr operator rep() {
       return std::chrono::duration_cast<Duration>(time).count();
    }
};

using s_ = dc<std::chrono::seconds>;
using us_ = dc<std::chrono::microseconds>;

// And so on ...

template <us_::rep N>
struct S {
};

int main()
{
    auto t0 = std::chrono::high_resolution_clock::now();
    // do some stuff
    auto t1 = std::chrono::high_resolution_clock::now();
    std::cout << "Time in seconds : " << s_(t1 - t0) << "s\n";
    std::cout << "Time in microseconds : " << us_(t1 - t0) << "µs\n";
    S<us_(10us)> us;
    (void)us;
    return 0;
}

[live demo]