拆包/包装操作员

问题描述 投票:0回答:1

我正在寻找实现打包/拆包运算符的各种方法。举个例子:

*[1,2,3]    --> 1,2,3     (one array scalar value unpacked to three values)
*1,2,3      --> [1,2,3]   (three values packed to one scalar array value)

这是语言中常见的运算符吗?如果有,通常如何表示?

其他可能的条款:

  • 解构/结构化
  • 开箱/包装
c++ parsing compiler-construction operator-keyword language-design
1个回答
2
投票

实现这一目标的方法取决于语言。

在 python 中,可以使用元组对值进行打包/解包:

mytuple = (1,2,3)   # Packing into a tuple
(a,b,c) = mytuple   # Unpacking
print(f'{a}, {b}, {c}')

在c++11中,可以使用

std::tie()
:

来完成
#include <iostream>
#include <tuple>

int main()
{
    auto mytuple = std::tuple<int,int,int>{1,2,3}; // Packing into a tuple
    int a, b, c;
    std::tie(a,b,c) = mytuple;                     // Unpacking (std::tie)
    std::cout << a << " " << b << " " << c << std::endl;
    return 0;
}

并且,在 c++17 及更高版本中,可以使用结构化绑定:

#include <iostream>
#include <tuple>

int main()
{
    auto mytuple = std::tuple{1,2,3}; // Packing into a tuple
    auto[a,b,c] = mytuple;            // Unpacking (structured binding)
    std::cout << a << " " << b << " " << c << std::endl;
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.