Reputation: 5728
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) {};
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.
Upvotes: 4
Views: 1303
Reputation: 40140
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)
Upvotes: 5
Reputation: 75853
C++14 supports generic lambdas:
std::function<void(int foo, float bar)> somefunc = [](auto&&...) {};
somefunc(42, 4711.0f);
Upvotes: 8