0

I pretend to write a class which can act as a variant type. Everything is working fine, but when I try to assing a string, the method that gets called is the one with bool as a parameter:

class value_t {
public:
    value_t operator=(const int& integer) {
        std::cout<<"integer"<<std::endl;
        return *this;
    };
    value_t operator=(const std::string& str) {
        std::cout<<"string"<<std::endl;
        return *this;
    };
    value_t operator=(const bool& boolean) {
        std::cout<<"boolean"<<std::endl;
        return *this;
    };

};

value_t val;
val = "Hola mundo";

And the output is:

boolean

Why is not the string assign operator method get called?

Thank you

raululm
  • 105
  • 1
  • 1
  • 10
  • 2
    Because `"Hola mundo"` isn't a `std::string`. – tkausl Apr 19 '19 at 16:17
  • It is what I thought first, but with “(const char* str)” wasn’t working either. And I created a constructor method with std::string as parameter, and the compiler recognized it as a std::string – raululm Apr 19 '19 at 16:20

1 Answers1

2

A string literal like "Hola mundo" is a const char [], which decays to const char *.

The language standard defines an implicit conversion from any pointer to a bool.

The compiler chooses your bool operator as a better choice because calling your std::string operator would require the compiler to construct a temporary std::string object, while calling the bool operator does not.

To do what you want, add another operator for const char * so the compiler doesn't have to convert at all (it can optionally call the std::string operator if desired):

value_t operator=(const char* str) {
    std::cout << "char*" << std::endl;
    return *this;
};

value_t operator=(const char* str) {
    return operator=(std::string(str));
};

Otherwise, you have to pass in a std::string explicitly:

val = std::string("Hola mundo");

On a side note, your operators should be returning a value_t& reference instead.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thank you. The duplicated question given by Praetorian and your answer were both right. I googled before answering, and didn’t find it. By the other way, sure I did a mistake when I ve tried (char* str) constructor method...because now is working perfectly. Thank you all. – raululm Apr 19 '19 at 16:37