boost::optional<std::string> 和来自 char[] 的隐式构造函数

boost::optional<std::string> and implicit constructor from char[]

本文关键字:char 构造函数 lt optional std string boost gt      更新时间:2023-10-16

我已经习惯了通过以下方式初始化std::字符串,让编译器计算出所涉及的魔力

std::string my_string = "hello";

以下内容将不起作用,因为这两种类型之间没有明确的转换:

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

然而,这确实有效:

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

现在,是否没有办法对隐式调用的单个arg构造函数进行daisychain以允许第二种形式?我之所以这么问(不过我不想详细地打扰你),是因为有一大堆类需要填充可选成员。必须明确地键入所有内容似乎是一种负担(我不太担心自己,但我正在开发开源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

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

最简单的解决方案:提供多个构造函数,一个采用char const*或更好的std::string,一个使用boost::optional

如果你希望每个参数都有这种可能性,那么最好只对ctor进行模板化。

template<class A1, class A2, class A3 /*, ..., class AN*/>
Class1(A1 const& a1, A2 const& a2, A3 const& a3 /*, ... , AN const& aN*/)
  : _member1(a1)
  , _member2(a2)
  , _member3(a3)
/*, ...
  , _memberN(aN)*/
{ /* ... */ }

顺便说一句,您不应该为未使用的optional传递NULL,而应该传递boost::none