Search code examples
c++templatesvariadic-templatesvariadic-functions

c++ templated class with functionpointer to variadic function


I want to implement a spooler/worker class in c++ that has a function to push new tasks into the class to have them executed by a background thread. The task gets appended to a queue and if the worker isn't running it is started.

For better reuse i want to use a variadic template arguments for variadic tasks, but i have trouble formulating the template header.

template <void (*TFunction)(typename ... TParams)> //a parameter pack is not allowed here
class worker
{
public:
    push(TParams... args);
};
template <typename ... TParams, void (*TFunction)(TParams...)> //template parameter pack not at end of parameter list
class worker
{
public:
    push(TParams... args);
};

I have two ideas that would work, but i don't like either.

template <typename ... TParams>
class worker
{
public:
    worker(void(*function)(TParams...)): function_(function) { }
    push(TParams... args);

private:
    const void (*function_)(TParams...);
};

template <typename ... TParams>
struct variadic
{
    template <void*(TFunction)(TParams...)>
    class worker {
    public:
        push(TParams... args);
    };
};

Is there a way to accept a function with variadic parameters with a single template header?

Thank you, everyone


Solution

  • With specialization:

    template <auto value>
    class worker;
    
    template <typename ... TParams, void (*F)(TParams...)>
    class worker<F>
    {
    public:
        void push(TParams... args);
    };
    

    Demo