Why are there two implicit conversions that differ only in the return constant?

Consider the following code:

#include <string>

class WrapperString
{
public:
    WrapperString(const std::string& str) : str_(str) {}

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

    std::string get() const { return str_; }
    // error C2373: 'WrapperString::get' : redefinition; different type modifiers
    // const std::string get() const { return str_; }

private:
    std::string str_;
};

int main (int, char *[])
{
    WrapperString w( "Hello" );
    std::string foo = w; // disabling either implicit conversion makes this work
    return 0;
}

Why is it WrapperStringreally compiled, given that two implicit conversions differ only in their constness? This result cannot be achieved by declaring a named method.

By the way, this is VS2010.

EDIT . To be clear, I added methods get()as a logical counterexample because of why it makes no sense to have two implicit conversions.

+4
source share
2 answers

Why is the WrapperString really compiling, given that the two implicit conversions differ only in their constant.

: operator std::string operator const std::string , , get .

$3[basic]/4: " - [...] conversion-function-id"

$12.3.2.1[class.conv.fct]/1:

conversion-function-id:
    operator conversion-type-id

, , .

 std::string s1 = w.operator std::string();
 std::string s2 = w.operator const std::string();
 std::string s3 = w.get(); // which get?
+5

, const, . .

, .

+4

Source: https://habr.com/ru/post/1524778/


All Articles