Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5975695
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T21:07:20+00:00 2026-05-22T21:07:20+00:00

When reading <ratio> and <chrono> I tried to imagine a Length -type that protects

  • 0

When reading <ratio> and <chrono> I tried to imagine a Length-type that protects against accidental conversion errors.

This is what I got:

#include <iostream>
#include <ratio>
using namespace std;

template<typename Scale>
struct Length  {
  long long val_;
  Length(long long val) : val_{val} {}
  Length() = default;
  Length(const Length&) = default;
  Length& operator=(const Length&) = default;
  // conversion
  template<typename Scale2>
  Length(const Length<Scale2> &other)
    : val_{ other.val_*(Scale2::num*Scale::den)/(Scale2::den*Scale::num) }
  { }
  // access
  long long value() const { return val_; }
}; 
typedef Length<ratio<1>> m;
typedef Length<kilo> km;
typedef Length<milli> mm;
typedef Length<ratio<1000,1094>> yard;

To be used like this

int main() {
  km len_km = 300;
  mm len_mm = len_km;
  cout << " millimeter:" << len_mm.value() << endl;
  cout << " m:" << m{len_km}.value() << endl;
  cout << " yd:" << yard{len_km}.value() << endl;
}

And now I could add all the + and * operations to get really comfortable… 🙂

I wonder:

  • Is there an easier access to the arithmetic facilities that duration and time_point define in <chrono> anyway? Can I use those reduce the effort for Length?
  • The compile-time constant (Scale2::num*Scale::den)/(Scale2::den*Scale::num) seems dangerous in the conversion constructor (fraction/underflow?), but I can not figure a better metaprogramming way, Any hints here?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T21:07:21+00:00Added an answer on May 22, 2026 at 9:07 pm
    • Is there an easier access to the
      arithmetic facilities
      that
      duration and time_point define in
      <chrono> anyway? Can I use those
      reduce the effort for Length?

    For “mixed mode” arithmetic and comparisons you can take advantage of common_type<T1, T2>::type for defining return types. duration specializes common_type to be the greatest common divisor of Period1 and Period2, where Period1 and Period2 are the two ratios involved in an arithmetic or comparison operation. You might use it like:

    template <typename Scale1, typename Scale2>
      typename std::common_type<Length<Scale1>, Length<Scale2>>::type
      operator+(Length<Scale1> x, Length<Scale2> y);
    

    Unfortunately you’ll have to reinvent how to get the greatest common divisor of two ratios at compile time. Start with compile-time gcd and lcm meta-functions for unsigned long long.

    Hmm… or you might be able to base your specialization of common_type on the one already done for duration. You could reinterpret the resultant duration‘s period as a scale factor for your Length. I haven’t prototyped this, just an idea.

    • The compile-time constant
      (Scale2::num*Scale::den)/(Scale2::den*Scale::num) seems dangerous in the conversion
      constructor
      (fraction/underflow?),
      but I can not figure a better
      metaprogramming way, Any hints here?

    Agreed. duration handles this with:

    template <class Rep2, class Period2>
      constexpr duration(const duration<Rep2, Period2>& d);
    

    Remarks: This constructor shall not
    participate in overload resolution
    unless treat_as_floating_point<rep>::value is true or both
    ratio_divide<Period2, period>::den is
    1 and treat_as_floating_point<Rep2>::value is false.
    [ Note: This requirement prevents
    implicit truncation error when
    converting between integral-based
    duration types. Such a construction
    could easily lead to confusion about
    the value of the duration. — end note]

    I.e. you need to enable_if your Length conversion constructor such that it only exists if the conversion is exact (if you want to base your length on integral types). For the conversion to be exact, the conversion factor (Scale2::num*Scale::den)/(Scale2::den*Scale::num) must be computable without division (except division by 1). You can use ratio_divide to do this division for you, and then the resulting denominator must be 1 (for an exact conversion).

    enable_if<ratio_divide<Scale2, Scale1>::type::den == 1, ...>
    

    This is a great project for learning ratio! Have fun! 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Reading through this excellent article about safe construction techniques by Brain Goetz, I got
Reading some questions here on SO about conversion operators and constructors got me thinking
I've got a couple books that I'm reading on AJAX, but still quite new.
Reading over the responses to this question Disadvantages of Test Driven Development? I got
Reading the Scala by Example book and there is this example when Martin explains
i was reading a tutorial from ray wenderlich website and i found this loop
Have gleaned much help from this site from reading the various posts over the
Ok, I asked this question and got excellent code example as answer. The code
There are sometimes errors like this when using SQL Server: Transaction (Process ID 54)
I was reading the answer to this question , but it solve the problem

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.