Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't a conversion function work with std::string?

Tags:

c++

Consider the following class which contains a conversion function for the std::string type:

class SomeType
{
    public:

    SomeType(char *value)
    {
        _str = value;
    }

    operator std::string()
    {
        return std::string(_str);
    }

    private:
    char *_str;
};

The following snippet fails to compile with the error: no operator "==" matches these operands

int main(int argc, char* argv[])
{
    SomeType a("test");

    if (a == std::string("test")) // ERROR on this line
    {
        int debug = 1;
    }

    return 0;
}

I realize I could define an operator== method that accepts std::string operand, but why doesn't the conversion function work?

like image 904
Julius Avatar asked Jul 14 '13 23:07

Julius


2 Answers

The problem is that std::string is in fact a template and as such I imagine that it's comparison operator is also a template. And in that case the standard as I recall states that no implicit conversion will happen for the required arguments, which means you'd have to cast SomeType to string yourself for it to be called.

As stated in Item 46 of Effective C++:

[...], because implicit type conversions are never considered during template argument deduction. Never. Such conversions are used during function calls, yes, but before you can call a function, you have to know which functions exist. [...]

You can find more info here.

like image 80
Borgleader Avatar answered Nov 19 '22 09:11

Borgleader


std::string is actually typedef to std::basic_string<char, i_do_not_remember>

There no operator == that get just std::string It's template one

template<...>
bool operator (basic_string<...>& a, basic_string<...>& b) {
    //
}

But template types can't be deduced here. You may cast it manually:

if (static_cast<std::string>(a) == std::string("test")) 
like image 25
RiaD Avatar answered Nov 19 '22 10:11

RiaD