如何将向量(或类似内容)传递到可变参数模板中
How to pass a vector (or similar) into a variadic template
假设我有以下代码:
template <typename... Args>
void DoSomething(const Args&... args)
{
for (const auto& arg : {args...})
{
// Does something
}
}
现在假设我从另一个函数调用它,并希望传入一个std::vector
(或者以某种方式修改向量,使其可以与此一起使用(
void DoSomethingElse()
{
// This is how I'd use the function normally
DoSomething(50, 60, 25);
// But this is something I'd like to be able to do as well
std::vector<int> vec{50, 60, 25};
DoSomething(??); // <- Ideally I'd pass in "vec" somehow
}
有没有办法这样做?我也考虑过使用 std::initializer_list
而不是可变参数模板,但问题仍然存在,我无法传入现有数据。
谢谢。
这是一种使用 SFINAE 的方法。传递一个元素,就会假设它是在ranged for-loop
中工作的东西。
如果你传递几个参数,它会构造一个向量并迭代它。
#include <iostream>
#include <type_traits>
#include <vector>
template <typename... Args, typename std::enable_if<(sizeof...(Args) > 1), int>::type = 0>
void DoSomething(const Args&... args)
{
for (auto& a : {typename std::common_type<Args...>::type(args)...})
{
cout << a << endl;
}
}
template <typename Arg>
void DoSomething(Arg& arg)
{
for (auto a : arg)
{
std::cout << a << std::endl;
}
}
int main() {
DoSomething(10, 50, 74);
std::vector<int> foo = {12,15,19};
DoSomething(foo);
return 0;
}
假设语法DoSomething({50, 60, 25})
是可以接受的,你可以首先为容器编写一个非可变参数函数模板:
template <typename T>
void DoSomething(const T& coll)
{
for (const auto& arg : coll) {
// ...
}
}
然后,一个用于std::initializer_list<>
的非可变参数函数模板:
template<typename T>
void DoSomething(const std::initializer_list<T>& lst)
{
for (const auto& elem: lst) {
// ...
}
}
它们可以通过以下方式使用:
void DoSomethingElse()
{
std::vector<int> vec{50, 60, 25};
std::list<int> lst{50, 60, 25};
// 1st function template
DoSomething(vec);
DoSomething(lst);
// 2nd function template
DoSomething({50, 60, 25});
}
为了避免代码重复,第二个函数模板可以从 std::initializer_list
参数创建一个std::vector
,然后使用该向量调用另一个函数模板:
template<typename T>
void DoSomething(const std::initializer_list<T>& lst)
{
std::vector<T> vec(lst);
DoSomething(vec);
}
相关文章:
- 在不传递参数数量且只有3个点的情况下,如何使用变差函数
- 如何使用可变参数模板强制转换每个变体类型
- 关于如何在具有单个参数的变体构造中选择替代方案?
- 调用参数排列不变函数 f(i++, i++)
- 参数归纳与标准::变体
- 模板化回调参数的逆变,如 C# 中的逆变
- 如何在没有参数包的情况下编写变差函数
- 通过具有嵌套类的工厂类获取多个变异类模板参数包
- 获取模板参数的成员变量值列表
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- 如何定义变体<x,y,z>提取模板参数的子类型
- 正确对齐内存模板,参数顺序不变
- 递归中不同参数类型的变元模板函数
- 通过函数指针传递给变差函数的参数会更改其值
- 提升预定义为带有参数的全局 lambda 的变体访问者
- 使用可变参数模板参数提升变体访问者
- boost ::变体 - 为什么模板参数比const字符串参数具有更高的优先级
- 将变参数包中的值加载到临时数组中
- 使用额外参数提升变体访客
- 从变长参数列表中提取std::string