forward variable Argument list to mock std::thread

Viewed 73

I want to mock my threads and wrote therefor an Adapter that just forward everything I need to std::thread. I am failing to do so for the constructor. I tried following:

class ThreadAdapter {
public:
    template< class Function, class... Args >
    explicit ThreadAdapter(Function&& f, Args&&... args) : thread_(f, args) {
    }

    virtual ~ThreadAdapter() = default;

   virtual  bool joinable() {
        return thread_.joinable();
    }

    virtual void join() {
        thread_.join();
    }

private:
    std::thread thread_;
};

Unfortunately this does not compile. My idea to forward the parameters in the constructor seems not to be valid, the compiler seems not to like the variable argument list. Does anybody have an idea how I can solve this?

bests

Sascha

2 Answers

As Daniel says, you need to forward your arguments and expand your parameter pack, like this:

template< class Function, class... Args >
explicit ThreadAdapter(Function&& f, Args&&... args) :
    thread_(std::forward <Function> (f),
    std::forward <Args...> (args...)) {
}

Then it works.

Thanks Daniel and Paul, it worked for me.

Just to complete my mcok I extended it by a factory where I also have a creation method. In this method I also forward the parameters:

template< class Function, class... Args >
std::shared_ptr<ThreadAdapter> createThread(Function&& f, Args&&... args) {
    return std::make_shared<ThreadAdapter>(std::forward<Function>(f), std::forward<Args...>(args...));
}
Related