Mads Midtlyng
Mads Midtlyng

Reputation: 131

C++ std::function syntax issues

I am trying to store a function pointer to be callbacked later like so:

Task->Sync->SetPeriodicTask( &TaskAssigner::ReadAndRelay );

TaskAssigner class declares void ReadAndRelay() and it holds a SyncManager* Sync object.

(It may be odd, but the child object Sync needs to call back to its parent class' function at certain intervals).

I attempt it like this:

void SyncManager::SetPeriodicTask(std::function<void()> func) {
    CB_func_periodic = func;
    //CB_func_periodic = std::bind(&func, this, std::placeholders::_1);
}

Member variable declaration (SyncManager.h):

private:
    using func = std::function<void()>;
    func CB_func_periodic;

I am not sure what is the correct syntax here, as I get so many errors. Tried searching the errors, but I couldn't find an answer that suits my case, and I don't want the parameter of SetPeriodicTask(..) to be too complicated for other users to write. How should I approach this?

Upvotes: 1

Views: 116

Answers (1)

M.M
M.M

Reputation: 141554

Here is some sample code based on the details you have posted so far:

#include <functional>

using func = std::function<void()>;

struct S
{
    func CB_func_periodic;
    void SetPeriodicTask( func f ) { CB_func_periodic = f; }
};

struct R
{
    void ReadAndRelay() {}
    S s;
};

int main()
{
    R r;
    r.s.SetPeriodicTask( [&] { r.ReadAndRelay(); } );
}

The argument to SetPeriodicTask should be a Callable, because that function calls it. The address of member function is not callable.

The code should be structured so that the periodic task cannot be invoked after r is destroyed.

Upvotes: 2

Related Questions