如何将向量(或类似向量)传递到可变参数模板中 [英] 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
(或以某种方式修改向量,使其可以与此结合使用)
Now let's say I'm calling this from another function, and want to pass in an std::vector
(or somehow modify the vector in such a way that it could be used with this)
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
而不是可变参数模板,但是问题仍然在于我无法传递现有数据.
Is there anyway to do this? I've also considered using std::initializer_list
instead of variadic templates, but the issue still remains that I have no way to passing in existing data.
谢谢.
推荐答案
这里是使用SFINAE的一种方法.传递一个元素,就可以认为它是在范围内for-loop
中起作用的一个元素.
Here is one approach that uses SFINAE.
Pass one element and it will be assumed it's something that works in a ranged for-loop
.
如果您传递几个参数,它将构造一个向量并对其进行迭代.
If you pass several arguments it constructs a vector and iterates over that.
#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;
}
这篇关于如何将向量(或类似向量)传递到可变参数模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!