gpt4 book ai didi

c++ - boost::optional 和来自 char[] 的隐式构造函数

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

我已经习惯了通过让编译器找出所涉及的魔法来以下列方式初始化 std::strings

std::string my_string = "hello";

以下将不起作用,因为两种类型之间没有显式转换:

boost::optional<std::string> my_optional_string = "hello";

但这确实有效:

boost::optional<std::string> my_optional_string = std::string("hello");

现在,难道没有办法菊花链隐式调用的单参数构造函数以允许第二种形式吗?我问的原因(虽然我不想用细节打扰你)是有一大堆类需要填充可选成员。必须显式输入所有内容似乎是一种负担(我不太担心自己,但我正在开发一个开源 API,并希望尽可能地为我的用户提供舒适感)。任何建议表示赞赏。


编辑:对不起大家,我是新手,应该提供更清晰的代码示例。我有一些类(不是我自己建模的,只是用 C++ 实现的),其中包含要填充的可选成员,如下所示:

Class Class1 {
public:
Class1(const boost::optional<std::string>& arg_1, /*... ,*/ const boost::optional<std::string>& arg_n );
};

我希望我的 API 用户能够指定的是:

Class1 my_class("hello","there",NULL,"stackoverflow");
/* ( Note: NULL is actually risky here, as some classes might also have members of type boost::optional<int> ) */

而不是:

Class1 my_class(std::string("hello"),/*or*/boost::optional<std::string>("there"),boost::optional<std::string>(),std::string("stackoverflow"));

再次感谢。

最佳答案

由于构造函数被标记为explicit ,你为什么不明确地调用构造函数? boost::optional<std::string> my_optional_string("hello");

编辑后

Xeo 已经提供了解决方案,也许你也可以为你的构造函数使用默认参数:

Class1(boost::optional<std::string> = boost::optional<std::string>(), /*...*/)
Class1(std::string arg1, /*...*/) :
member1(arg1), /*member2(arg2), etc.*/

然后你就可以全部Class1像这样:

Class1 my_class;
Class1 my_class("hello", "there"); // Rest of arguments use boost::optional

但是,如果您必须提供许多构造函数和可能性,那么上述可能不是一个好的解决方案,您可以考虑将其模板化以减少您必须编写的代码量。

关于c++ - boost::optional<std::string> 和来自 char[] 的隐式构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11680582/

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