C++14 Create vector from variadic templates

  • A+

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}


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: