如何从函数中返回 std::可选<myclass>?

How to return std::optional<myclass> from a function?

本文关键字:lt myclass gt 可选 返回 std 函数      更新时间:2023-10-16

我似乎缺少一些非常简单的东西。以下是不起作用的:

#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,该类是默认情况下的公共成员的类。

另外,请记住,默认的构造函数和分配运算符通常更好,并且在您只是放置空的地方更具性能。