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

std::function extract and remove argument


I'm learning c++11/14 these days and it seems like a whole new language to me with all the great additions but I still can't quite make use of all these new features:

typedef std::function<void()> void_f;

typedef std::function<void(int a, void_f b)> f1;
typedef std::function<void(int a, std::function<void(void_f f)> c, void_f b)> f2; // this order is wanted

std::vector<f1> v;

void add(f1 f)
{
    v.push_back(f);
}

void add(f2 f)
{
     v.push_back(f) // ?
 // I want to extract 'void_f f' argument from std::function for later use 
//and remove std::function completely to get same signature as f1
}

I've been looking at std::move, std::bind, std::forward, std::placeholders but I can't seem to find anything like this. Maybe I should save longer version in vector and then bind empty lambda for shorter one?


Solution

  • No, you can save the "shorter" f1 in the vector if that's what you want:

    typedef std::function<void()> void_f;
    
    typedef std::function<void(int a, void_f b)> f1;
    typedef std::function<void(int a, std::function<void(void_f f)> c, void_f b)> f2;
    
    std::vector<f1> v;
    
    void add(f1 f)
    {
        v.push_back(f);
    }
    
    void add(f2 f)
    {
         v.push_back([](int a, void_f b) { f(a, [](){}, b); });
    } 
    

    You can't "remove" the extra argument of f2 but you can pass a no-op lambda. The outer lambda puts the remaining arguments a and b into the right order.