patterncppMinor
Is this a conforming implementation of duration_cast?
Viewed 0 times
thisimplementationconformingduration_cast
Problem
Sadly VS2012's
But I'm not entirely confident that it's correct.
duration_cast is broken, and I actually need the functionality which is broken. So, I wrote my own: template
ToUnit duration_cast_2(const std::chrono::duration& right)
{
typedef std::ratio_divide::type ratio;
typedef std::common_type::type, intmax_t>::type common_type;
return ToUnit(static_cast(static_cast(right.count()) * static_cast(ratio::num) / static_cast(ratio::den)));
}But I'm not entirely confident that it's correct.
Solution
I can't say for sure about the internal logic but I can point some problems or things that could be improved in your piece of code:
-
First of all,
-
-
I know that MSVC has not a full support for
-
First of all,
typename is missing before the names, making your code non-working with some compilers. I would also use using instead of typedef, but that's a mere matter of taste. Updated version:using ratio = typename std::ratio_divide::type;
using common_type = std::common_type::type, intmax_t>::type;-
std::common_type is variadic. You don't have to bother with nested std::common_types:using common_type = typename std::common_type::type;-
I know that MSVC has not a full support for
constexpr, but duration_cast is supposed to be constexpr (it should work with the November 2013 CTP though):template
constexpr ToUnit duration_cast_2(const std::chrono::duration& right)
{
// ...
}Code Snippets
using ratio = typename std::ratio_divide<Period, typename ToUnit::period>::type;
using common_type = std::common_type<typename std::common_type<typename ToUnit::rep, Rep>::type, intmax_t>::type;using common_type = typename std::common_type<typename ToUnit::rep, Rep, intmax_t>::type;template<typename ToUnit, typename Rep, typename Period>
constexpr ToUnit duration_cast_2(const std::chrono::duration<Rep, Period>& right)
{
// ...
}Context
StackExchange Code Review Q#22836, answer score: 5
Revisions (0)
No revisions yet.