0

I'm trying to pass a function (f1) through another function (f2), while not having to specify f1.

Example Code

Class C {
    private: std::deque<T*> queue;
    public: edit_queue(std::function<void(T*)> f1, void* input);
};

C::edit_queue(...){
    queue.f1(input);
}

However this doesn't compile with error:

no member named 'f1' in 'std::__1::deque<T *, std::__1::allocator<T *> >

I would like to be able to do both:

edit_queue(push_back, T* input);     (1)

and

edit_queue(push_front, T* input);    (2)

I've tried passing a function pointer as well:

public: edit_queue(void (*f1)(T*), T* input);
c::edit_queue(...){queue.f1(input);};

and

private: std::deque<T*>* queue;
...

but got the same result.

In addition, is it also possible to not have to specify the inputs of f1 as well? For instance, (1) and (2) would work as well as:

edit_queue(pop_back);
  • "while not having to specify f1." do you mean without fixing the **type** of `f1` ? Passing `f1` to some method without specifying `f1` is a little weird. Moreoever what is `T`? – 463035818_is_not_an_ai Feb 18 '19 at 21:03
  • Without specifying f1; so f1 can be any member function of deque. T is the type that is being stored in the queue. – user11081080 Feb 18 '19 at 21:03
  • Please read about [mcve]. It is rather hard to make sense of this fragments – 463035818_is_not_an_ai Feb 18 '19 at 21:04
  • 1
    you cannot pass a parameter to a function without "specifiying" what the parameter is – 463035818_is_not_an_ai Feb 18 '19 at 21:04
  • Possible duplicate of [How can I pass a member function where a free function is expected?](https://stackoverflow.com/questions/12662891/how-can-i-pass-a-member-function-where-a-free-function-is-expected) if I understand correctly what you're looking to do. – scohe001 Feb 18 '19 at 21:04
  • Looks to me like you want to use a lambda. Then you call `edit_queue` like `edit_queue([](auto& q) { q.push_front(some_value); });` or `edit_queue([](auto& q, auto&& val) { q.push_front(val); }, some_value);` – NathanOliver Feb 18 '19 at 21:06
  • Is it possible then to specify the input and outputs of the function and pass that function through? E.g. pass any function of type std::function through? – user11081080 Feb 18 '19 at 21:07
  • Not if the function is going to be a member function. – NathanOliver Feb 18 '19 at 21:11

1 Answers1

0

f1 isn't a method of queue so your code won't compile. You can have different handling of edit_queue by passing a lambda instead and calling it:

template <typename Container, typename T>
void edit_queue(std::function<void(Container&, const T&)> func, const T& data)
{
  func(queue, data);
}

Then call it with a lambda that calls push_back or push_front.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122