将参数包转换为向量

Boc*_*iek 2 c++ c++11 c++14

我试图理解 C++ 中的可变参数模板,但我在以下示例中迷失了:想象一个函数foo(T, T, T, T)它采用相同类型 T 的可变参数数量并将它们转换为向量。知道如何实现一个吗?

它应该像这样工作

foo<int>(1,2,3,4) returns std::vector<int> x{1,2,3,4}
foo<double>(0.1,0.2,0.3) returns std::vector<double> x{0.1,0.2,0.3}
Run Code Online (Sandbox Code Playgroud)

max*_*x66 6

如果T在编译时已知值,您可以将它们作为模板参数传递并编写类似

template<typename T, T ... Is>
void foo() {
   std::vector<T> x { { Is.. } };

   for( auto xx:x )
      std::cout << xx << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

被称为

foo<int, 2, 3, 5, 7>();
Run Code Online (Sandbox Code Playgroud)

否则,您必须将它们作为参数传递;就像是

template <typename T, typename ... ARGS>
void foo (ARGS const & ... args) {    
   std::vector<T> x { { args... } };

   for( auto xx:x ) 
      std::cout << xx << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

被称为

foo<int>(2, 3, 5, 7);
Run Code Online (Sandbox Code Playgroud)

或者(T从第一个参数推导出类型)

template <typename T, typename ... ARGS>
void foo (T const & arg0, ARGS const & ... args) {    
   std::vector<T> x { { arg0, args... } };

   for( auto xx:x ) 
      std::cout << xx << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

被称为

foo(2, 3, 5, 7);
Run Code Online (Sandbox Code Playgroud)

- 编辑 -

OP写

它应该像这样工作

foo<int>(1,2,3,4) returns std::vector<int> x{1,2,3,4}
foo<double>(0.1,0.2,0.3) returns std::vector<double> x{0.1,0.2,0.3}
Run Code Online (Sandbox Code Playgroud)

所以我想你可以简单地写

template <typename T, typename ... ARGS>
std::vector<T> foo (ARGS const & ... args)
 { return { args... }; }
Run Code Online (Sandbox Code Playgroud)