简体   繁体   English

C ++ 14从可变参数模板创建向量

[英]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> . 并且想要编写从对象读取字段“name”的函数并将它们作为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} 输出: {a1.name, a2.name, a3.name, a4.name}

A really simple expansion that works in C++11: 一个非常简单的扩展,适用于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. 所发生的是,向量是用初始化列表构造的,由变量参数包构造 ,同时为每个可变元素应用函数 (成员访问运算符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM