Problem solved by updating to the latest version of LLVM, which fully supports all C++11 features.
why explicit operator std::string does not work
-
09-06-2023 - |
Frage
I have a class which has a conversion operator for type std::string marked as explicit. Here is the class
class MyClass {
public:
// methods ...
explicit operator std::string() const {
// convert to string ...
}
}
Problem is when I use static_cast on a variable of type MyClass I get the error "No matching conversion for static_cast from 'MyClass' to 'std::string aka …" I seem to have the same problem when I define conversion operators for any custom type. Is the explicit modifier only defined for conversion to primitive types or is this another compiler bug.
Lösung 2
Andere Tipps
Here is an example
#include <iostream>
#include <string>
class MyClass {
public:
// methods ...
explicit operator std::string() const {
return "Hello World";
}
};
int main()
{
MyClass obj;
std::cout << static_cast<std::string>( obj ) << std::endl;
return 0;
}
The output is
Hello World
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow