Uniform initialization by tuple

Ale*_*ph0 26 c++ stl stl-algorithm uniform-initialization stdtuple

Today, I arrived at a situation, where I have a vector of tuples, where the tuples might contain several entries. Now I wanted to convert my vector of tuples to a vector of objects, such that the entries of the tuples will exactly match the uniform initialization of my object.

The following code does the job for me, but it is a bit clumsy. I'm asking myself if it might be possible to derive a generic solution that can construct the Objects if the tuples matches exactly the uniform initialization order of the objects.

This might be a very desirable functionality, when the number of parameters to pass grows.

#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;
}
Run Code Online (Sandbox Code Playgroud)

Sta*_*nny 18

Provide Object an std::tuple constructor. You can use std::tie to assign your members:

template<typename ...Args>
Object(std::tuple<Args...> t) {
    std::tie(s, i, d) = t;
}
Run Code Online (Sandbox Code Playgroud)

Now it gets automatically constructed:

std::transform(values.begin(), values.end(), std::back_inserter(objs), 
    [](auto v) -> Object {
        return { v };
    });
Run Code Online (Sandbox Code Playgroud)

To reduce the amount of copying you might want to replace auto v with const auto& v and make the constructor accept a const std::tuple<Args...>& t.


Also, it's good practise to access the source container via const iterator:

std::transform(values.cbegin(), values.cend(), std::back_inserter(objs), ...

  • @BartekPL这是`std :: tuple`的典型布局。该模板称为[参数包](https://en.cppreference.com/w/cpp/language/parameter_pack)。`std :: tie`构造一个引用元组,使分配成为可能。 (4认同)

lub*_*bgr 13

这是一种非侵入式版本(即,不触摸Object),它提取了指定数据成员的数量。请注意,这依赖于聚合初始化。

template <class T, class Src, std::size_t... Is>
constexpr auto createAggregateImpl(const Src& src, std::index_sequence<Is...>) {
   return T{std::get<Is>(src)...};
}

template <class T, std::size_t n, class Src>
constexpr auto createAggregate(const Src& src) {
   return createAggregateImpl<T>(src, std::make_index_sequence<n>{});
}
Run Code Online (Sandbox Code Playgroud)

您可以这样调用它:

std::transform(values.cbegin(), values.cend(), std::back_inserter(objs),
     [](const auto& v)->Object { return createAggregate<Object, 3>(v); });
Run Code Online (Sandbox Code Playgroud)

或者,没有包装的lambda:

std::transform(values.cbegin(), values.cend(), std::back_inserter(objs),
   createAggregate<Object, 3, decltype(values)::value_type>);
Run Code Online (Sandbox Code Playgroud)

正如@Deduplicator指出的那样,上述帮助器模板实现的一部分std::apply,可以代替使用。

template <class T>
auto aggregateInit()
{
   return [](auto&&... args) { return Object{std::forward<decltype(args)>(args)...}; };
}

std::transform(values.cbegin(), values.cend(), std::back_inserter(objs),
    [](const auto& v)->Object { return std::apply(aggregateInit<Object>(), v); });
Run Code Online (Sandbox Code Playgroud)

  • 不,`std :: copy`不起作用,因为正在进行_is_转换,所以您要从另一种类型构造一个类型,当用目标类型外部的函数(模板)完成操作时,该类型不能隐含。 (3认同)

Jar*_*d42 12

从C ++ 17开始,您可以使用std :: make_from_tuple

std::transform(values.begin(),
               values.end(),
               std::back_inserter(objs),
               [](const auto& t)
        {
            return std::make_from_tuple<Object>(t);
        });
Run Code Online (Sandbox Code Playgroud)

注意:需要适当的构造函数Object