foo
foo

Reputation: 406

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.

Upvotes: 1

Views: 52

Answers (1)

Davidbrcz
Davidbrcz

Reputation: 2397

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

Upvotes: 3

Related Questions