"string_literal"解析为布尔值,但不解析为 std::string,当编译器选择函数的重载版本时
"string_literal" resolved as bool but not as std::string, when compilier selects overloaded version of function
有一个类
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))
{
}
然后,如果你的实际构造函数需要在这里做任何没有显示的工作(虽然你没有完全展示一个最小、完整和可验证的示例,但你的努力已经足够好了),就不会有任何额外的代码重复。
再三考虑,这可能是您正在寻找的"不错"解决方案。可以说,这正是嵌套构造函数的用途。
相关文章:
- 如何使用默认参数等选择模板专业化
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 选择要调用的构造函数
- C++选择排序算法中的逻辑错误
- QTreeView幻灯片多选后无法使用单击选择
- cppcheck在const std::string[]上引发警告
- 无法获取菜单选择以运行函数.C++
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 将std::string传递给WriteConsole API
- 在C++中,如何通过几种类型从元组中选择多个元素
- 为std::string的某个索引赋值
- 讨论 - 创建矩阵时的数组与向量的向量 - 什么是最实用的选择
- C++:使用委托构造函数时选择"const char *"与"std::string&qu
- 使用STD :: String和字符数组之间的选择
- 有选择地替换 C++ 中 std::string 中的 (") 双引号
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- "string_literal"解析为布尔值,但不解析为 std::string,当编译器选择函数的重载版本时
- 如何使用选择排序对向量进行<string>排序
- String对象数组的c++选择排序
- 基于string的派生类选择