Search code examples
c++c++11c++14std-function

std::function variable arguments in one vector/map


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?


Solution

  • Create a new lambda matching the new signature and add that instead:

    void add(f2 f)
    {
        m.push_back( [g = std::move(f)](int a, int /* unused */){ g(a); } );
    }