【问题标题】:problem with function on the lside of an assignment作业方面的功能问题
【发布时间】:2021-02-05 20:56:13
【问题描述】:

我在测试用例中定义了这个元组,

std::tuple<int, string, string, double> t1 = { 1321, "xxxx", "xxxx", 1.68 }

我必须编写一个函数解包,我应该能够做到这一点:

int key; string first_name; string last_name; double height;
unpack(key, first_name, last_name, height) = t1;

我无法更改上面的定义,因为它们在测试用例中,我无法修改。

我知道函数应该这样声明:

&unpack()

我应该使用模板,但我不知道如何使用。感谢您的回答。

【问题讨论】:

  • 这已经存在:std::tie
  • 听起来并不多,但举一个简单的例子,我想你有答案了,@tkausl
  • 你需要写函数unpack还是你需要一个你描述的方式可以使用的函数?
  • 我不能使用 std::tie 因为它没有出现在我的函数应该通过的测试用例中。所以我必须编写函数 unpack 但我不知道该怎么做。
  • 如果您在收到答案后更改问题,建议您明确更改内容。

标签: c++ function templates


【解决方案1】:

如果您有权访问C++17,则可以使用结构化绑定:

#include <tuple>
#include <string>

std::tuple<int, string, string, double> tpl = { 1321, "xxxx", "xxxx", 1.68 };

const auto& [a,b,c,d] = tpl;

如果没有,那么按照@tkausl 的建议,您可以使用std::tie

...
int a;
string b,c;
double d;

std::tie(a,b,c,d) = tpl;

语法很笨拙,因为您必须事先定义变量,因此无法将它们设为const

【讨论】:

  • 我必须编写函数,因为元组的定义和赋值都在测试用例中,我无法修改。
【解决方案2】:

我必须编写函数,因为元组的定义和赋值都在测试用例中,我无法修改。

template <class... Args>
constexpr decltype(auto) unpack(Args&&... args) noexcept
{
    return std::tie(std::forward<Args>(args)...);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 2018-08-16
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多