【问题标题】:returning three values from a function从函数返回三个值
【发布时间】:2015-11-20 18:22:15
【问题描述】:

您好,我想实现元组。 让我知道这出了什么问题以及如何正确实施它。我想从一个函数返回三个值,其中第一个值是整数,最后一个值是数组。

template <typename T1, typename T2, typename T3>
struct t_untuple
{
    T1& a1;
    T2& a2;
    T3& a3;
    explicit t_untuple(T1& a1, T2& a2, T3& a3) : a1(a1), a2(a2), a3(a3) { }

t_untuple<T1, T2, T3>& operator = (const tuple <T1, T2, T3>& p)
    {
        a1 = p.first;
        a2 = p.second;
        a3 = p.third;
        return *this;
    }
};

// Our functor helper (creates it)
template <typename T1, typename T2, typename T3>
t_untuple<T1, T2, T3> unpair(T1& a1, T2& a2, T3& a3)
{
    return t_unpair<T1, T2, T3>(a1, a2, a3);
}

帮我解决这个问题。

我在 const tuple & p 处得到 无法解析符号“元组”,因此 p.third 也是一个错误

【问题讨论】:

  • 当你尝试使用它时会发生什么?
  • 为什么不创建一个包含 int,int,std::array 的类(假设 T 变化)
  • 你能帮忙看看怎么做吗?我不确定我现在可以如何进行。
  • 你有什么理由不使用std::tuple

标签: c++ tuples stdtuple


【解决方案1】:

如果你知道要返回什么类型,为什么不使用简单的结构:

template <typename T>
struct return_type {
    int a;
    int b;
    std::array<T> c;
}

【讨论】:

    【解决方案2】:

    假设数组类型是不变的。要么使用 std::tuple

    std::tuple<int,int,std::array<std::string>> MyFunc()
    

    这里是手册页http://en.cppreference.com/w/cpp/utility/tuple

    或创建具体类

    struct IIA
    {
        int a;
        int b;
        std::array<std::string> arr;
    }
    
    IAA Myfunc(){}
    

    【讨论】:

    • 他已经在使用std::tuple,他想创建帮助器来解压值
    【解决方案3】:

    您似乎尝试使用 unpairstd::pair 扩展代码:

    t_untuple<T1, T2, T3>& operator = (const tuple <T1, T2, T3>& p)
        {
            a1 = p.first;
            a2 = p.second;
            a3 = p.third;
            return *this;
        }
    };
    

    但元组的访问字段以不同的方式完成:

    t_untuple<T1, T2, T3>& operator = (const std::tuple <T1, T2, T3>& p)
        {
            a1 = std::get<0>(p);
            a2 = std::get<1>(p);
            a3 = std::get<2>(p);
            return *this;
        }
    };
    

    您还需要在复制粘贴中将unpair 替换为untuple

    template <typename T1, typename T2, typename T3>
    t_untuple<T1, T2, T3> untuple(T1& a1, T2& a2, T3& a3)
    {
        return t_untuple<T1, T2, T3>(a1, a2, a3);
    }
    

    别忘了#include &lt;tuple&gt;,你必须确保你的编译器至少处于c++11模式

    【讨论】:

    • 您好,我在实现您的代码时遇到此错误。错误:'tuple' 没有命名类型 t_untuple& operator = (const tuple & p)
    • 更改为 std::tuple 并且不要忘记包含我添加到答案中的内容
    猜你喜欢
    • 2014-06-26
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多