[英]C++ user-defined literals for any type
For now, user-defined literals accept a limited set of types as input parameter (see here ). 现在,用户定义的文字接受一组有限的类型作为输入参数(请参见此处 )。 Is there any plan to accept any type as input parameter, and if not why is that ?
有没有计划接受任何类型作为输入参数,如果不是,那是为什么呢?
For example, I might want to be able to get a std::chrono::duration in different format (seconds, milliseconds, etc), and would do something like 例如,我可能希望能够以不同的格式(秒,毫秒等)获得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;
}
Maybe you could make use of helper structs instead: 也许您可以改用辅助结构:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.