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 wants = A()to also work). - Also if I remove the template method,
s = A();works.
Can someone please explain what is triggering the different behaviours?