Search code examples
c++classc++11templatesvariadic-templates

variadic template (with class and funtion) fails to complie


I need to implement a self-register functionality, and I want to get the parameters. OK, my description is not clear, here is my code.

#include <vector>

template<typename T, int... Param>
class Demo
{
public:
    static std::vector<int> __GetParam()
    {
        std::vector<int> vec;
        Push(vec, Param);
        return vec;
    }

private:
    static void Push(std::vector<int>& vec, int v)
    {
        vec.emplace_back(v);
    }

    template<int... Rest>
    static void Push(std::vector<int>& vec, int v, Rest... rest) // error here
    {
        vec.emplace_back(v);
        Push(vec, rest...);
    }
};

int main()
{
    auto vec = Demo<char, 1, 2, 3, 4>::__GetParam();
    return 0;
}

Could anyone explain the problem? Thanks in advance.


Solution

  • Just expand the parameter pack into the vector directly

    static std::vector<int> __GetParam()
    {
        std::vector<int> vec{Param...};
        return vec;
    }
    

    If you want to keep your original idea, you need to call Push with each argument of the pack. One way to do it is the Variadic template initilizer_list trick

        auto l = {(Push(vec, Param),0)...};
    

    Then, you just need to fix the rest of the code

    static void Push(std::vector<int>& vec, int v)
    {
        vec.push_back(v);
    }
    
    template<int... Rest>
    static void Push(std::vector<int>& vec, int v) // error here
    {
        vec.push_back(v);
        Push(vec, Rest...);
    }