gpt4 book ai didi

c++ - 字符串文字重载

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:51:07 26 4
gpt4 key购买 nike

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

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 的接口(interface):

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++ - 字符串文字重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23139783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com