【问题标题】:How to write custom make_tuple function?如何编写自定义 make_tuple 函数?
【发布时间】:2021-04-20 09:03:24
【问题描述】:
struct Person {
    int id;
    std::string name;
    std::string email;
}

我想将 struct 转换为自定义元组,例如

auto tuple<...> my_make_tuple1(const Person& p) {
    return std::make_tuple(p.id);
}
auto tuple<...> my_make_tuple2(const Person& p) {
    return std::make_tuple(p.id, p.name);
}

那些元组函数怎么写?

【问题讨论】:

  • 只需删除 tuple&lt;...&gt; 部分,它应该可以编译。
  • 删除元组<...> part works@rustyx

标签: c++ templates tuples c++17


【解决方案1】:

更简单的方法是使用auto:

struct Person {
    int id;
    std::string name;
    std::string email;
};


auto as_tuple(const Person& p) {
    // return std::tie(p.id, p.name); // Possibly
    return std::make_tuple(p.id, p.name);
}

【讨论】:

    【解决方案2】:

    通过这个你可以制作元组

     struct Person {
            int id;
           std::string name;
            std::string email;
        };
        
        
        auto as_tuple(const Person& p) {
    
            return std::make_tuple(p.id, p.name);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2011-06-11
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多