Rufus
Rufus

Reputation: 5566

How can I make a function pointer parameter no-op by default?

Given my function that takes a function pointer as parameter

void call_func(std::function<void()>func) {
    func();
}

The most straight forward way is something like

void no_op() {
    ;
}

void call_func(std::function<void()>func = no_op) {
    func();
}

Is there a cleaner way to do this so that I can avoid creating the literally useless no_op function?

Upvotes: 2

Views: 490

Answers (1)

songyuanyao
songyuanyao

Reputation: 173014

You can use an empty lambda, which could be also wrapped by std::function. e.g.

void call_func(std::function<void()>func = []{}) {
    func();
}

Upvotes: 6

Related Questions