specify default value of std::function

C++Lambda

C++ Problem Overview


void func(const std::function<void()>& f = empty)
{
    if(f)
        f();
}

what is the 'empty' should be? I use [](){} . But technically, that is not empty, the f() will execute.

C++ Solutions


Solution 1 - C++

void func(const std::function<void()>& f = {}) {
    if(f) f();
}

LIVE DEMO

Solution 2 - C++

const std::function<void()>& f = nullptr

or

const std::function<void()>& f = std::function<void()>()

Solution 3 - C++

I would use a nullptr for the empty case. It can be used because you never use full function objects but only pointers to them, so func(f1); will be in fact func(&f1) => you will always pass pointers to func, so nullptr is IMHO the best candidate.

This compiles and run:

void func(const std::function<void()>& f = nullptr)
{
    if(f)
        f();
}

The alternative of using a default function would be:

void func(const std::function<void()>& f = std::function<void()>()) {
    try {
        f();
    }
    catch(std::bad_function_call e) {
    }
}

using exception catching. The choice between the 2 mainly depends on whether you expect the empty case to occur; almost never: go with exception vs. sometimes: test before call.

As question mentions if (f), use nullptr

Solution 4 - C++

You can try like this:

const std::function<void()> & f = std::function<void()>()

As Basile added, the standard says:

> § 20.8.11.1 Class bad_function_call [func.wrap.badcall] > > 1/ An exception of type bad_function_call is thrown by > function::operator() (20.8.11.2.4) when the function wrapper object > has no target.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjeanView Question on Stackoverflow
Solution 1 - C++101010View Answer on Stackoverflow
Solution 2 - C++nh_View Answer on Stackoverflow
Solution 3 - C++Serge BallestaView Answer on Stackoverflow
Solution 4 - C++Rahul TripathiView Answer on Stackoverflow