2

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()); // ??
}
Barry
  • 286,269
  • 29
  • 621
  • 977
Zhihar
  • 1,306
  • 1
  • 22
  • 45

1 Answers1

5

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • 1
    Thank you, tell me, how do I declare the `std::barrier` as a member of a class? (how use pointer to `std::barrier`)? – Zhihar Mar 15 '21 at 19:32
  • `Error C2338 N4861 [thread.barrier.class]/5: is_nothrow_invocable_v shall be true` :( – Zhihar Mar 15 '21 at 20:00