c++ - "string_literal" resolved as bool but not as std::string, when compilier selects overloaded version of function -
have class
class { 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 value "world" resolved boolean , should specify std::string
int main() { a("hello","world"); cout << "a.type_: " << (a.type_ == a::type::string ? "string" : "boolean") << endl; = a("hello",std::string{"world"}); cout << "a.type_: " << (a.type_ == a::type::boolean ? "string" : "boolean") << endl; } so need overload class constructor const char*.
a(const std::string &name, const char *s) : name_(name), type_(type::string), str_(s) {} any other nice solution?
update. runable here. contains 2 solutions , sam varshavchik's. uncomment 1 of them achieve result.
unfortunately, there no "nice solution". c++ not have reputation being "nice".
the best thing here use nested constructor, @ least won't have additional work constructor has do:
a(const std::string &name, const char *s) : a(name, std::string(s)) { } then, if actual constructor here needs work didn't show (although didn't quite show minimal, complete, , verifiable example, effort enough), there won't additional code duplication.
on second thought, might "nice" solution you're looking for. can argued nested constructors for.
Comments
Post a Comment