"string_literal"解析为布尔值,但不解析为 std::string,当编译器选择函数的重载版本时

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

本文关键字:string 选择 函数 编译器 重载 版本 literal 布尔值 std      更新时间:2023-10-16

有一个类

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) {}

当构造值为"world"的类时,它被解析为布尔值,我显然应该指定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;
}     

所以我需要为const char*重载类构造函数。

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

还有其他不错的解决方案吗?

更新。在这里无法。它包含我和Sam Varshavchik的2个解决方案。取消注释其中的 1 个以达到结果。

不幸的是,没有"好的解决方案"。C++没有"好"的名声。

在这里,您可以做的最好的事情是使用嵌套构造函数,因此至少您不必执行构造函数必须执行的任何其他工作:

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

然后,如果你的实际构造函数需要在这里做任何没有显示的工作(虽然你没有完全展示一个最小、完整和可验证的示例,但你的努力已经足够好了),就不会有任何额外的代码重复。

再三考虑,这可能是您正在寻找的"不错"解决方案。可以说,这正是嵌套构造函数的用途。