Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++14 Create vector from variadic templates

Suppose, I have a structure

struct A
{
   std::string name;
};

and want to write function which reads field "name" from objects and return them as std::vector<std::string>. Is it possible to do this by variadic templates (or any non-iterative method). My goal is something like this:

template<typename... Ts>
std::vector<std::string> function(Ts... ts)
{
    ...
}

in program:

    A a1, a2, a3, a4;
    function(a1, a2, a3, a4);

output: {a1.name, a2.name, a3.name, a4.name}

like image 590
Piodo Avatar asked Dec 17 '18 11:12

Piodo


1 Answers

A really simple expansion that works in C++11:

template <typename ... Ts>
std::vector<std::string> function(Ts&& ... ts)
{
    return {std::forward<Ts>(ts).name...};
}

(forwarding references not required)

What happens is, that the vector is constructed with initializer list, constructed from the variadic parameter pack, while applying a function (member access operator) for each variadic element.

like image 192
LogicStuff Avatar answered Nov 06 '22 06:11

LogicStuff