Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the compiler generate an empty default function for an std::function

Tags:

c++

In this code, I'd like ... to be a non-verbose way of saying "empty function with the matching arguments":

std::function<void(int foo, float bar)> somefunc  = ...;

I want it to generate code corresponding to this but without repeating the argument types:

std::function<void(int foo, float bar)> somefunc  = [](int, float) {};

Background

I can declare and initialize an std::function this way:

std::function<void(int foo, float bar)> somefunc;

Then I can call it like this:

if(somefunc) {
    somefunc(42, 4711.0f);
}

But the if statement bloats the code (and I'm not that fond of null pointers), so I can define the function with a default empty implementation:

std::function<void(int foo, float bar)> somefunc  = [](int, float) {};

and then the call will be simply:

somefunc(42, 4711.0f);

But it gets a little repetitive to repeat the arguments like this, so I'd like something that generates that empty implementation instead.

like image 847
Martin Vilcans Avatar asked Oct 25 '25 05:10

Martin Vilcans


2 Answers

C++14 supports generic lambdas:

std::function<void(int foo, float bar)> somefunc  = [](auto&&...) {};
somefunc(42, 4711.0f);
like image 55
bolov Avatar answered Oct 26 '25 19:10

bolov


You can define a null function:

struct nullfunc_t
{
    template<class F>
    operator std::function<F>()
    { return [](auto&&...){}; }
} nullfunc;

Now, this becomes legal and do The Right Thing(TM):

int main()
{
    std::function<void(int, float)> somefunc1 = nullfunc;
    std::function<void(float, int)> somefunc2 = nullfunc;
    somefunc1(1, 2.f);
    somefunc2(1.f, 2);
}

(demo)

like image 37
YSC Avatar answered Oct 26 '25 20:10

YSC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!