Unpacking variadic template parameters into initializer list

拥有回忆 提交于 2019-12-06 00:03:24
auto device = new T{ allArguments };

just needs to be

auto device = new T{ args... };

In T{ args... } args... will expand the parameter pack to arg0, arg1, ..., argn for you.

You can see this working with

template <typename... Args>
std::vector<int> make_vector(Args... args)
{
    return {args...};
}

int main()
{
    auto foo = make_vector(1,2,3,4);
    for (auto e : foo)
        std::cout << e << " ";
}

Edit to add perfect forwarding version

template <typename... Args>
std::vector<int> make_vector(Args&&... args)
{
    return {std::forward<Args>(args)...};
}

My C++14 answer, as a minimal working example

#include <initializer_list>
#include <utility>
#include <vector>
#include <type_traits>
#include <iostream>

struct example {
    template <typename ...Args, typename T = std::common_type_t<Args...>>
    static std::vector<T> foo(Args&& ...args) {
        std::initializer_list<T> li{std::forward<Args>(args)...};
        std::vector<T> res{li};
        return res;
    }
};

int main() {
    std::vector<int> v1 = example::foo(1,2,3,4);
    for(const auto& elem: v1)
        std::cout << elem << " ";
    std::cout << "\n";
}

You need to edit this for your needs a bit, to your code structure that is. But note that vectorconstructor takes initializer_list and that list is generated from parameter pack in that static foo method.

Edit: In your case, as others noted, you can just directly forward your parameter pack to your call. My answer shows passing them to an initializer_list.

So in fact, you can just do

static std::vector<T> foo(Args&& ...args) {
    std::vector<T> res{std::forward<Args>(args)...};
    return res;
}

and those arguments will be implicitly converted to an initializer_list. I explicitly showed the construction of an initializer_list from a parameter pack.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!