use*_*435 4 c++ string boost char optional
我已经习惯了通过让编译器找出所涉及的魔法来以下列方式初始化std :: strings
std::string my_string = "hello";
Run Code Online (Sandbox Code Playgroud)
以下操作无效,因为两种类型之间没有明确的转换:
boost::optional<std::string> my_optional_string = "hello";
Run Code Online (Sandbox Code Playgroud)
但这确实有效:
boost::optional<std::string> my_optional_string = std::string("hello");
Run Code Online (Sandbox Code Playgroud)
现在,有没有办法菊花链式隐式调用单arg构造函数来允许第二种形式?我问的原因(我不想打扰你的细节)是有一大堆类可以填充可选成员.必须明确键入所有内容似乎是一种负担(我并不担心自己,但我正在开发一个开源API,并希望尽可能多地为我的用户提供安慰).任何建议表示赞赏.
编辑:对不起伙计我是新手,应该提供更多澄清代码示例.我有一些类(没有自己建模,只是在C++中实现它们),可选成员要填充,如下所示:
Class Class1 {
public:
Class1(const boost::optional<std::string>& arg_1, /*... ,*/ const boost::optional<std::string>& arg_n );
};
Run Code Online (Sandbox Code Playgroud)
我希望我的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> ) */
Run Code Online (Sandbox Code Playgroud)
并不是:
Class1 my_class(std::string("hello"),/*or*/boost::optional<std::string>("there"),boost::optional<std::string>(),std::string("stackoverflow"));
Run Code Online (Sandbox Code Playgroud)
再次感谢.
由于构造函数已标记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.*/
Run Code Online (Sandbox Code Playgroud)
然后你们都可以Class1这样:
Class1 my_class;
Class1 my_class("hello", "there"); // Rest of arguments use boost::optional
Run Code Online (Sandbox Code Playgroud)
但是,如果你必须提供许多构造函数和可能性,也许上面可能不是一个好的解决方案,你可以考虑模仿它来减少你必须编写的代码.
| 归档时间: |
|
| 查看次数: |
4183 次 |
| 最近记录: |