字符串文字重载
String Literal Overloading
是否可以重载构造函数,该构造函数在初始值设定项列表中使用时只接受空白字符串?
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
}
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 为什么传递文字 3 会选择 int 重载而不是短重载?
- 为什么用整数文字调用重载的 ambig(long) 和 ambig(无符号 long)是不明确的
- 构造函数在尝试支持文字时重载歧义
- 字符串文字重载
- 字符串文字匹配bool重载,而不是std::String