将参数包转换为向量 [英] converting parameter pack into a vector
本文介绍了将参数包转换为向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图理解C ++中的可变参数模板,但在以下示例中迷失了:想象一个函数 foo(T,T,T,T),该函数采用相同参数的可变参数输入T并将其转换为向量。知道如何实现吗?
I am trying to understand variadic templates in C++ and I am lost in the following example: Imagine a function foo(T, T, T, T) which takes variadic number of arguments of the same type T and converts them into a vector. Any idea how to implement one?
它应该像这样
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}
推荐答案
如果 T
值在编译时是已知的,您可以将它们作为模板参数传递并编写类似
If the T
values as known at compile-time, you can pass they as template parameters and write something like
template<typename T, T ... Is>
void foo() {
std::vector<T> x { { Is.. } };
for( auto xx:x )
std::cout << xx << std::endl;
}
称为
foo<int, 2, 3, 5, 7>();
否则,您必须将它们作为参数传递;
Otherwise you have to pass they as arguments; something like
template <typename T, typename ... ARGS>
void foo (ARGS const & ... args) {
std::vector<T> x { { args... } };
for( auto xx:x )
std::cout << xx << std::endl;
}
称为
foo<int>(2, 3, 5, 7);
或也(从中推导类型 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;
}
称为
foo(2, 3, 5, 7);
-编辑-
OP写入
它应该像这样
It should work like this
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}
所以我想您可以简单地写
So I suppose you can simply write
template <typename T, typename ... ARGS>
std::vector<T> foo (ARGS const & ... args)
{ return { args... }; }
这篇关于将参数包转换为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文