-2

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?

Petar
  • 1,034
  • 1
  • 12
  • 18

1 Answers1

1

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • that was what I've done first but then argument is completely lost. Is there any way to get ahold of it somehow? – Petar Aug 12 '15 at 08:50
  • @juzerKicker: Which argument is lost? The whole reason why we provide an empty lambda as a second argument is because there wasn't an argument in the first place. `f2 f` needs 3 arguments, and the users of `vector` will only provide 2 arguments. – MSalters Aug 12 '15 at 12:38
  • std::function has f argument, which is lambda, which may contain code written by hand, usage would be like: c([]{} _some_code_here}). I would like to save that before 'removing' it by calling no-op lambda later on. I think I will do that on the fly once c is called. – Petar Aug 12 '15 at 13:39
  • 1
    @juzerKicker: Higher-order functions can be confusing. `std::function` doesn't have an `f` argument, it _needs_ an argument. – MSalters Aug 12 '15 at 18:57