在初始化列表中使用时,是否可以重构一个只接受空字符串的构造函数?
struct null_ptr_type;
struct str
{
str(null_ptr_type*) {}
str(const char(&)[1]) {}
};
struct config
{
str s;
};
int main()
{
config c1 = {0}; // Works, implicit conversion to a null pointer
config c2 = {str("")}; // Works
config cx = {str("abc")}; // Fails (as desired)
config c3 = {""}; // Fails with no conversion possible
}
有没有办法让c3
的语法工作而不接受非空字符串?鉴于c1
有效,我不明白为什么不这样做。我在这里缺少一些禁止这种情况的规则吗?
答案 0 :(得分:0)
使用C ++ 11和"统一初始化语法"假设您能够修改struct config
的接口:
struct config
{
str s;
config(str s) : s(s) {}
};
int main()
{
config c1 = {0}; // Works, implicit conversion to a null pointer
config c2 = {str("")}; // Works
config cx = {str("abc")}; // Fails (as desired)
config c3 = {""}; // Works
}