C++ Conversion operators


Example

You can overload type operators, so that your type can be implicitly converted into the specified type.

The conversion operator must be defined in a class/struct:

operator T() const { /* return something */ }

Note: the operator is const to allow const objects to be converted.

Example:

struct Text
{
    std::string text;

    // Now Text can be implicitly converted into a const char*
    /*explicit*/ operator const char*() const { return text.data(); }
    // ^^^^^^^
    // to disable implicit conversion
};

Text t;
t.text = "Hello world!";

//Ok
const char* copyoftext = t;