Initializing a std::barrier with a class member function

Viewed 326

How do you initialize a std::barrier with a class member function?

class CMyClass {
private:
    void func() {
    }

public:
    void start() {
    }
}

void CMyClass::start() {
    std::barrier<??> barrier(threads_count, &func()); // ??
}
1 Answers

The completion function of a barrier has to be invocable with zero arguments, which means you can't just pass a pointer to non-static member function (such a function still needs an argument: the class instance). Instead, you have to provide a lambda:

std::barrier barrier(threads_count, [this]{ func(); });

Class template argument deduction (CTAD) will deduce the class template parameter from the type of the lambda, so you don't have to worry about it.

Related