如何从函数中返回 std::可选<myclass>?
How to return std::optional<myclass> from a function?
我似乎缺少一些非常简单的东西。以下是不起作用的:
#include <optional>
class Alpha {
Alpha() { }
Alpha(const Alpha& that) { }
Alpha(Alpha&& that) { }
~Alpha() { }
static std::optional<Alpha> go() {
return Alpha();
}
};
我遇到的错误是:
no suitable user-defined conversion from "Alpha" to "std::optional<Alpha>" exists
T in optional<T> must satisfy the requirements of Destructible
'return': cannot convert from 'Alpha' to 'std::optional<Alpha>'
我缺少什么,你能解释一下为什么?
您将所有构造函数私有化。std::optional
无法移动或复制您的课程。要解决此问题,只需这样做:
class Alpha {
public: // <--- there
Alpha() { }
Alpha(const Alpha& that) { }
Alpha(Alpha&& that) { }
~Alpha() {}
private:
static std::optional<Alpha> go() {
return Alpha();
}
};
您也可以使用struct
,该类是默认情况下的公共成员的类。
另外,请记住,默认的构造函数和分配运算符通常更好,并且在您只是放置空的地方更具性能。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 如何创建一个类,以便向量工作 std::vector<MyClass<int>> v{ 1,2,3 };
- 反转C++ foo(MyClass &) vs foo(const MyClass &)
- 如何显式调用运算符<<
- 从 json 字符串将 QVariant 转换为 QList<MyClass>
- #include "MyClass.h" 和 #include ".myclass.h" 有什么区别
- MyClass obj = MyClass();'MyClass()'在这里指的是临时对象吗?
- 'return':无法从'const class myClass'转换为'class myClass &'
- 如何初始化 const std::vector<MyClass>
- "delete p"和"p->~MyClass()"之间的区别
- 模板操作员&lt;未打电话
- C / CUDA中的模板方法是3个角括号(&lt;&lt;&lt;)
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- 'class MyClass' 在尝试定义静态结构实例时不会命名类型
- 注意:候选:MyClass:MyClass(const MyClass&) 错误
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;