Milad
Milad

Reputation: 43

C++ multiple conversion operators

I defined a class as below with two member variables and two conversion operators (operator float and operator chrono::microseconds). But the code below only works if I comment out the float operator. Otherwise, it throws an error (cannot convert type). I can't figure out why?

#include <iostream>
#include <chrono>

using namespace std::chrono_literals;

class Peak {
public:
  Peak (std::chrono::microseconds t, float magnitude)
  : t_(t),
    magnitude_(magnitude)
  {
  };

  std::chrono::microseconds get_t() { return t_; }
  //have to comment this out or I get an error
  operator float() { return magnitude_; }
  operator std::chrono::microseconds() {
      return t_;
  }
private:
  std::chrono::microseconds t_{2us};
  float magnitude_;
};

int main()
{
  Peak a{3us, 100};
  std::cout
    << "t is "
    << static_cast<std::chrono::microseconds>(a).count();
}

Upvotes: 2

Views: 408

Answers (1)

Nikos C.
Nikos C.

Reputation: 51832

Looks like a compiler bug in GCC 7.3 and older. A workaround seems to be building using the -std=c++17 flag. Alternatively, making the float conversion operator explicit also fixes it:

explicit operator float() const { return magnitude_; }

(It's always a good idea to mark these const, by the way.)

Update:

Actually, just making these operators const seems to fix it already without the need to make the float one explicit nor to build with -std=c++17.

Upvotes: 3

Related Questions