c++ - "string_literal"当编译器选择函数的重载版本时,解析为 bool 而不是 std::string

标签 c++

上课

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”的类时,它被解析为 bool 值,显然我应该指定 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) {}

还有其他好的解决方案吗?

更新。 可运行 here .它包含我和 Sam Varshavchik 的 2 个解决方案。取消注释其中 1 个以获得结果。

最佳答案

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

您在这里可以做的最好的事情是使用嵌套构造函数,这样至少您不必做构造函数必须做的任何额外工作:

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

然后,如果您实际的构造函数在这里需要做的任何工作都没有显示(尽管您没有完全显示 Minimal, Complete, and Verifiable Example ,您的努力已经足够好了),就不会有任何额外的代码重复。

转念一想,这可能是您正在寻找的“不错”的解决方案。可以说这正是嵌套构造函数的用途。

关于c++ - "string_literal"当编译器选择函数的重载版本时,解析为 bool 而不是 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247364/

相关文章:

c++ - QPainter与Qt::AlignCenter不能正确居中文本

c++ - 了解带有常量的预处理器宏

c++ - 从 uint32 或 uchar 数组创建 ARGB QImage

c++ - 使用 clang 共享库中的额外模块名称符号

c++ - 通过内存捕获 MSN 聊天记录

c++ - 代码无法识别 "#include"语句

c++ - 怀疑在构造函数中工作的一个缺点

c++ - 如何使用函数指针或虚函数来允许另一个程序员定义函数的实现?

java - 使用 IAudioEndpointVolume

c++ - 有没有办法检测一个函数是否存在并且可以在编译时使用?