简体   繁体   English

std::make_tuple() 是否不适用于 std::optional 类型的对象?

[英]Does std::make_tuple() not work with objects of type std::optional?

This is the source code:这是源代码:

using namespace std;

class obj {
    public:
        obj() = default;
        obj(int i) : i_{i} {}

        int         I()  const  {return i_;}
        int const & rI() const  {return i_;}
        void    I(int i)        {i_ = i;}
        void    show()  const   {cout << "addr = " << this << ", i_ = " << I() << endl;}

    private:
        int i_{0};
};

struct {
    optional<obj> o_0 {nullopt};
    optional<obj> o_1 {nullopt};
    optional<obj> o_2 {nullopt};

    void set_o0(obj o_) {o_0 = o_;}
    void set_o1(obj o_) {o_1 = o_;}
    void set_o2(obj o_) {o_2 = o_;}

    tuple<optional<obj>, optional<obj>, optional<obj>> get_obj() {
        return make_tuple<o_0, o_1, o_2>;
    }
} opts_;
  

Trying to return a std::tuple composed of type std::optional<> does not seem to work.试图返回一个由std::optional<>类型组成的std::tuple似乎不起作用。 The following error message is reported which is not particularly that helpful.报告了以下错误消息,它不是特别有用。 Can anyone help?任何人都可以帮忙吗?

<source>: In member function 'std::tuple<std::optional<obj>, std::optional<obj>, std::optional<obj> ><unnamed struct>::get_obj()':
<source>:40:27: error: use of 'this' in a constant expression
   40 |         return make_tuple<o_0, o_1, o_2>;
      |                           ^~~
<source>:40:32: error: use of 'this' in a constant expression
   40 |         return make_tuple<o_0, o_1, o_2>;
      |                                ^~~
<source>:40:37: error: use of 'this' in a constant expression
   40 |         return make_tuple<o_0, o_1, o_2>;
      |                                     ^~~
<source>:40:16: error: cannot resolve overloaded function 'make_tuple' based on conversion to type 'std::tuple<std::optional<obj>, std::optional<obj>, std::optional<obj> >'
   40 |         return make_tuple<o_0, o_1, o_2>;
      |                ^~~~~~~~~~~~~~~~~~~~~~~~~

std::make_optional is a function template. std::make_optional是一个 function 模板。 Its purpose is to deduce the tuples types from the parameters passed to it.它的目的是从传递给它的参数中推断出元组类型。

Rather than explicitly listing the template arguments you should let them be deduced from the parameter.与其明确列出模板 arguments,不如让它们从参数中推导出来。 And you need to actually call the function:您需要实际调用 function:

auto get_obj() {
    return std::make_tuple(o_0, o_1, o_2);
}

Note that you can use auto for the return type.请注意,您可以使用auto作为返回类型。 If you do not use the auto return type you do not need make_tuple (because as I said, its purpose is to deduce the tuples types, but when the type is already known this isnt required):如果您不使用auto返回类型,则不需要make_tuple (因为正如我所说,它的目的是推断元组类型,但是当类型已知时,这不是必需的):

std::tuple<std::optional<obj>, std::optional<obj>, std::optional<obj>> get_obj() {
    return {o_0, o_1, o_2};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM