0

How would I achieve the following JavaScript implementation of callbacks in C++? Below is taken from a JavaScript snippet. I'd like to achieve the same functionality:

var playAdBreak = function(adbreak, callback) 
{
    var x;
    playSingle(x, function() { playAdBreak.call(this, adbreak, callback); });
};

var playSingle = function(abc, callback) 
{

};

2 Answers 2

1

If you are under C++11 environment, you can use lambda, std::function. Below code doesn't have same functionality, but it can convert into like below except for : C++ lambda is not closure and there is no this for a function.

auto playSingle = [&](const T &abc, std::function<void()> callback) {

}

auto playAdBreak = [&](const Y &adbreak, std::function<void()) callback) {
  T x;
  playSingle(x, [=]() { playAdBreak(adbreak, callback); });
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much! But by any chance do you know an alternative way of implementing this? the trouble i'm having is passing the parameters into playAdBreak(adbreak, callback) as part of the callback function
1

The modest way of doing it that I can think is

void callBackDefinition()
{
    printf("I was called");
}

void callBackExecutor(void (*callBack))
{
    callBack();
}

main()
{
    callBackExecutor(&callBackDefinition);
    return 0;
}

1 Comment

Thanks for your answer. The trouble i'm actually having is passing the parameters into playAdBreak(adbreak, callback) as part of the callback function. Still trying to figure that out...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.