Search code examples
c++function-pointersnon-staticpass-by-pointer

How to pass a changing member function through another function?


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);

Solution

  • 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.