使用boost::optional失败
failed attempt of using boost::optional
我一直在尝试使用boost可选的函数,可以返回一个对象或null,我不能弄清楚。这是我目前所知道的。对于如何解决这个问题,我将不胜感激。
class Myclass
{
public:
int a;
};
boost::optional<Myclass> func(int a) //This could either return MyClass or a null
{
boost::optional<Myclass> value;
if(a==0)
{
//return an object
boost::optional<Myclass> value;
value->a = 200;
}
else
{
return NULL;
}
return value;
}
int main(int argc, char **argv)
{
boost::optional<Myclass> v = func(0);
//How do I check if its a NULL or an object
return 0;
}
更新:
这是我的新代码,我得到一个编译错误在value = {200};
class Myclass
{
public:
int a;
};
boost::optional<Myclass> func(int a)
{
boost::optional<Myclass> value;
if(a == 0)
value = {200};
return value;
}
int main(int argc, char **argv)
{
boost::optional<Myclass> v = func(0);
if(v)
std::cout << v -> a << std::endl;
else
std::cout << "Uninitilized" << std::endl;
std::cin.get();
return 0;
}
您的函数应该如下所示:
boost::optional<Myclass> func(int a)
{
boost::optional<Myclass> value;
if(a == 0)
value = {200};
return value;
}
你可以通过转换到bool
来检查它:
boost::optional<Myclass> v = func(42);
if(v)
std::cout << v -> a << std::endl;
else
std::cout << "Uninitilized" << std::endl;
不应该是value->a = 200
不,不是。从Boost.Optional.Docs:
T const* optional<T (not a ref)>::operator ->() const ; T* optional<T (not a ref)>::operator ->() ;
- 要求:*this is initialized
- 返回:指向所包含值的指针。
- 抛出:没有。
- 注意:需求是通过BOOST_ASSERT()断言的。
在operator->
定义中:
pointer_const_type operator->() const
{
BOOST_ASSERT(this->is_initialized());
return this->get_ptr_impl();
}
如果对象没有初始化,断言将失败。当我们写
value = {200};
我们用Myclass{200}
初始化值。
注意,value = {200}
要求支持初始化列表(c++ 11特性)。如果你的编译器不支持,你可以这样使用它:
Myclass c;
c.a = 200;
value = c;
或提供Myclass
的构造函数,int
作为参数:
Myclass(int a_): a(a_)
{
}
那么你可以直接写
value = 200;
相关文章:
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- gcc和c++17的过载解析失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 从父数组测试用例构造二叉树失败
- LibGit2 SSH身份验证失败
- 如何让LLDB在成功时退出,在失败时等待
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 函数模板参数推断使用 std::Optional 失败
- 使用boost::optional失败
- 继承虚拟函数的类的boost::optional失败的原因