字符串文字重载

String Literal Overloading

本文关键字:重载 文字 字符串      更新时间:2023-10-16

是否可以重载构造函数,该构造函数在初始值设定项列表中使用时只接受空白字符串?

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是有效的。我这里有没有遗漏一些禁止这样做的规则?

使用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
}