Question

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.

Was it helpful?

Solution 2

Problem solved by updating to the latest version of LLVM, which fully supports all C++11 features.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top