字符串文字重载

Dar*_*con 5 c++

在初始化列表中使用时,是否可以重构一个只接受空字符串的构造函数?

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
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在c3不接受非空字符串的情况下制作工作语法?鉴于有效,我不明白为什么不这样c1做.我在这里缺少一些禁止这种情况的规则吗?

mil*_*bug 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
}
Run Code Online (Sandbox Code Playgroud)