boost::optional<std::string> 和来自 char[] 的隐式构造函数
boost::optional<std::string> and implicit constructor from char[]
我已经习惯了通过以下方式初始化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
。
相关文章:
- std::string 构造函数如何处理固定大小的 char[]?
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- 构造函数 (C++) 中的 char 指针参数存在问题
- c ++ 如何在构造函数中初始化 char
- 当我尝试通过构造函数分配 char 数组时出现错误
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- C++:使用委托构造函数时选择"const char *"与"std::string&qu
- 替换 istrstream(char* s, std::streamsize n) 构造函数?
- 字符串或const char*,更有效地用作构造函数参数
- Picky STD :: String Char Array构造函数
- 带有字符串(使用char数组)参数的构造函数
- 如何在默认构造函数中将 char 数组初始化为 null
- 为什么 const char 数组成员的初始化在构造函数初始值设定项中不兼容
- C 构造函数从char*到int []/int*
- 将const char*传递到构造函数中,使得无效
- 如何创建一个构造函数,该构造函数吸收char阵列
- 在类构造函数中初始化 Char 数组成员C++
- 使用字符串文本初始化构造函数中的 std::array<char,x> 成员。海湾合作委员会错误?
- 如何修复GCC编译中的const char *构造函数转换链错误
- 为什么 QFile( "./test" ) 工作,尽管 [类 QFile] 没有 QFile(char* s) 构造函数