【发布时间】:2019-11-15 20:26:23
【问题描述】:
今天,我遇到了一种情况,我有一个元组向量,其中元组可能包含多个条目。现在我想将我的元组向量转换为对象向量,这样元组的条目将完全匹配我的对象的统一初始化。
以下代码为我完成了这项工作,但有点笨拙。我在问自己,如果元组与对象的统一初始化顺序完全匹配,是否有可能派生一个可以构造对象的通用解决方案。
当要传递的参数数量增加时,这可能是一个非常理想的功能。
#include <vector>
#include <tuple>
#include <string>
#include <algorithm>
struct Object
{
std::string s;
int i;
double d;
};
int main() {
std::vector<std::tuple<std::string, int, double>> values = { {"A",0,0.},{"B",1,1.} };
std::vector<Object> objs;
std::transform(values.begin(), values.end(), std::back_inserter(objs), [](auto v)->Object
{
// This might get tedious to type, if the tuple grows
return { std::get<0>(v), std::get<1>(v), std::get<2>(v) };
// This is my desired behavior, but I don't know what magic_wrapper might be
// return magic_wrapper(v);
});
return EXIT_SUCCESS;
}
【问题讨论】:
标签: c++ stl stl-algorithm stdtuple uniform-initialization