Here is what I try to achieve:
class MyClass
{
public:
using Callback = void(MyClass::*)(uint8_t idx);
void forEach(Callback callback);
private:
int m_buf[64];
int m_x;
int m_y;
MyObject m_object;
}
void MyClass::forEach(Callback callback)
{
size_t s = m_object.size();
for(size_t i = 0; i < s; i++)
callback(i);
}
void MyClass::f1()
{
forEach([this](uint8_t idx)
{
m_buf[idx]++;
});
}
void MyClass::f2()
{
forEach([this](uint8_t idx)
{
m_buf[idx] = m_x + m_y * idx;
});
}
So there are a bunch of ways to modify m_buf[]
. In order to avoid copying and pasting 'get size + for loop', I want to add a forEach
method and pass lambdas as callbacks.
this
is captured to have access to class members.
What is the right way to achieve the same result?
Thanks.
PS: compilation of this example returns error 'cannot convert ::lambda ....'
ANSWER: With "Passer By" answer, I finished with the code:
// Class declaration in header
using Callback = std::function<void(uint8_t)>;
void forEach(Callback callback);
// forEach() is as above
// forEach() call looks like
forEach([this](uint8_t idx) {
m_buf[idx] = m_x + m_y * idx;
});
Also I found some related questions-anwers which might be useful
Passing lambda as function pointer - "5gon12eder" answer.
C++ lambda with captures as a function pointer