Assigning to conversion operator fails - C++

Viewed 111

I'm trying to cast class A into a string as such:

#include <iostream>
#include <string>

class A {
public:
  std::string data_ = "hello world";

  A() {}

  operator std::string() const {
    return data_;
  }

  template <typename T>
  operator T() const {
    return data_;
  }
};

int main() {
  A();

  // This fails
  // std::string s;
  // s = A();

  std::string s = A(); // This works
  return 0;
}

What I'm trying to solve is the part where s = A();. It fails during compilation and the compiler tells me there is no '=' assigment operator that assigns A into a string.

What is interesting is:

  • if its a copy constructor is called (with std::string s = A();) the "conversion operator" kicks in and it works (but I want s = A() to also work).
  • Also if I remove the template method, s = A(); works.

Can someone please explain what is triggering the different behaviours?

1 Answers

The solution is simple. Make it explicit rather than an implicit conversion:

  template <typename T>
  explicit operator T() const {
    return data_;
  }

The advantage is now that all four possibilities work:

  std::string s;
  s = A();

  std::string s2 = A(); // This works
  std::string s3 = std::string(A());
  std::string s4;
  s4 = std::string(A());
Related