如何将向量(或类似内容)传递到可变参数模板中

How to pass a vector (or similar) into a variadic template

本文关键字:变参 参数 向量      更新时间:2023-10-16

假设我有以下代码:

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);
}