简体   繁体   中英

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

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<<; .

I guess you are using visual studio. Update it.

in Visual Studio is broken. It doesn't work with mixed type arithmetic, which, arguably, is one of the main features of . You get this error because one of the sides uses __int64 nanos and the other uses double nanos.

I recommend either dropping it in favor of a real C++ implementation, or using Boost.Chrono.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM