how could one do this in c++ today without using two separate holders?
typedef std::function<void(int a, int b)> f1;
typedef std::function<void(int a)> f2;
std::vector<f1> m;
void add(f1 f)
{
m.push_back(f);
}
void add(f2 f)
{
// add one more (unused) parameter to f2 so we can add f2 to f1 vector holder?
}
can we somehow overload f1 function to include different set of parameters? could this be solved by variadic templates nowdays or something similar?
Create a new lambda matching the new signature and add that instead:
This wraps a
std::function
in a lambda that ignores any extra args:it gets trickier if we don't want that needless layer of type erasure.
You need to find the longest prefix of
Args...
which you can invoke a given objectf
with, then invokef
with it. This involves some tricky metaprogramming.It is far easier if you ask the caller to pass in a signature:
which saves on possible overhead.
live example