字符串文字重载

时间:2014-04-17 17:35:17

标签: 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
}

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

1 个答案:

答案 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
}