If the T
在编译时已知的值,您可以将它们作为模板参数传递并编写类似的内容
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>();
否则你必须将它们作为参数传递;就像是
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写
它应该像这样工作
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}
所以我想你可以简单地写
template <typename T, typename ... ARGS>
std::vector<T> foo (ARGS const & ... args)
{ return { args... }; }