c++variadic

Using Variadic Function to pass args into a vector


I am trying to make a function that adds an unknown amount of objects to a vector. I am trying to accomplish it here by just passing ints, but I cannot get it to work. Does any one know how this can be done?

Code

#include <iostream>
#include <vector>

class Entity
{
public:
    std::vector<int> Ints;
    
    template <typename T, typename ... pack>
    void AddToVector(T first, pack ... argPack)
    {
        Ints.push_back(argPack...);
        
        for(auto& i : Ints)
            std::cout << i << "\n" << std::endl;
    };
};


int main()
{
    Entity e1;
    
    e1.AddToVector(1, 2, 3, 4, 5);
    return 0;
}

Error:

main.cpp: In instantiation of ‘void Entity::AddToVector(T, pack ...) [with T = int; pack = {int, int, int, int}]’:
main.cpp:32:33</span>:   required from here
main.cpp:20:9: error: no matching function for call to ‘std::vector::push_back(int&, int&, int&, int&)’

Solution

  • In C++11 and C++14, You can use something like this:

    private:
        void Internal_AddToVector()
        {
        }
    
        template <typename T, typename ... pack>
        void Internal_AddToVector(T first, pack... argPack)
        {
            Ints.push_back(first);
            Internal_AddToVector(argPack...);
        }
    
    public:
        template <typename ... pack>
        void AddToVector(pack ... argPack)
        {
            Internal_AddToVector(argPack...);
    
            for(auto& i : Ints)
                std::cout << i << "\n" << std::endl;
        }
    

    Alternatively:

    public:
        template <typename ... pack>
        void AddToVector(pack ... argPack)
        {
            for (auto& elem : {argPack...})
                Ints.push_back(elem);
    
            for(auto& i : Ints)
                std::cout << i << "\n" << std::endl;
        }
    

    In C++17 and later, you can use a fold expression instead:

    public:
        template <typename ... pack>
        void AddToVector(pack... argPack)
        {
            (Ints.push_back(argPack), ...);
    
            for(auto& i : Ints)
                std::cout << i << "\n" << std::endl;
        }