kyb
kyb

Reputation: 8201

"string_literal" resolved as bool but not as std::string, when compilier selects overloaded version of function

Have a class

class A {
public: //nested types
    enum Type {string,boolean};
public: //for simple debug
    std::string name_;
    enum Type type_;
    bool boo_;
    std::string str_;
public:
    A(const std::string &name, const std::string &s) : 
              name_(name), type_(Type::string), str_(s) {}
    A(const std::string &name, const bool &b) : 
              name_(name), type_(Type::boolean), boo_(b) {}

And when constructing class with value "world" it is resolved as boolean and I should obviously specify std::string

int main()
{
    A a("hello","world");
    cout << "a.type_: " << (a.type_ == A::Type::string ? "string" : "boolean") << endl;
    a = A("hello",std::string{"world"});
    cout << "a.type_: " << (a.type_ == A::Type::boolean ? "string" : "boolean") << endl;
}     

So I need to overload class constructor for const char*.

    A(const std::string &name, const char *s) : 
             name_(name), type_(Type::string), str_(s) {}

Any other nice solution?

Update. Runable here. It contains 2 solutions my and Sam Varshavchik's. Uncomment 1 of them to achieve result.

Upvotes: 1

Views: 66

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

Unfortunately, there is no "nice solution". C++ does not have a reputation for being "nice".

The best thing you could do here is to use a nested constructor, so at least you won't have to do any additional work the constructor has to do:

A(const std::string &name, const char *s)
    : A(name, std::string(s))
{
}

Then, if your actual constructor here needs to do any work didn't show (although you didn't quite show a Minimal, Complete, and Verifiable Example, your effort was good enough), there won't be any additional code duplication.

On second thought, this might be the "nice" solution you're looking for. It can be argued that this is exactly what nested constructors are for.

Upvotes: 3

Related Questions