K.K*_*der 5 c++ templates variadic-templates c++11
假设我有以下代码:
template <typename... Args>
void DoSomething(const Args&... args)
{
for (const auto& arg : {args...})
{
// Does something
}
}
Run Code Online (Sandbox Code Playgroud)
现在假设我从另一个函数调用它,并且想要传递一个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
}
Run Code Online (Sandbox Code Playgroud)
有办法做到这一点吗?我也考虑过使用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;
}
Run Code Online (Sandbox Code Playgroud)