Search code examples
c++structc++-chrono

C++ Errors involving outputting chrono duration


Here's the class I'm working with (Some parts cut out)

const int records = 7;

    class Timed {
    public:

        friend std::ostream& operator<<(std::ostream& os, Timed right) {
            for (int i = 0; i < records; i++) {
                os << right.eR[i].vName << " " << right.eR[i].duration << " " << right.eR[i].seconds << std::endl;
            }
            return os;
        }

    private:

        std::chrono::time_point<std::chrono::steady_clock> start, end;

        struct {
            std::string vName;
            std::string seconds;
            std::chrono::duration<float> duration;
        } eR[records];

    };

Basically, I'm trying to output the values of the anonymous struct. However, I get the error:

binary '<<': no operator found which takes a right-hand operand of type 'std::chrono::duration<float,std::ratio>1,1>>' (or there is no acceptable conversion)

I was wondering how I would be able to print this value for duration? Thanks in advance


Solution

  • In C++11/14/17, there is no streaming operator for chrono::duration types. You have two choices:

    1. Extract the .count():

    |

     os << right.eR[i].duration.count() << "s ";
    
    1. Use this open-source, header-only date/time library:

    |

    #include "date/date.h"
    // ...
    using date::operator<<;
    os << right.eR[i].duration << " ";
    

    The above datelib is now part of C++20, but is not yet shipping. Vendors are working on it. When you port to it, you can just drop the #include "date/date.h" and using date::operator<<;.