I want to use either push_front or push_back depending on user input. Is it possible to have that included in the function parameter, then write one function in order to save on memory?

2 Answers

JeJo On

Is it possible to have that included in the function parameter?

No. You can't.

A good explanation can be found in this discussion: Can I take the address of a function defined in standard library?

However, a workaround can be done by telling the function explicitly where the insertion should take place.

#include <iostream>
#include <deque>

enum class To{ front = 0, back };

void func(std::deque<int>& dq, const int value, const To where)
    if (where == To::front)
        // code
    else if(where == To::back)
        // code

And you call it

std::deque<int> dq;
func(dq, 1, To::back);
func(dq, 2, To::front);
Maxim Egorushkin On

It is possible using lambdas:

#include <deque>

void f(bool user_input) {
    using C = std::deque<int>;
    using FnType = void(*)(C&, int);
    FnType const fns[2] = {
        [](C& c, int value) { c.push_front(value); },
        [](C& c, int value) { c.push_back(value); }
    C q;
    fns[user_input](q, 1);
    fns[!user_input](q, 2);

In this examples, the closures created by lambda expressions have 0 captures and hence can be converted to plain function pointers. When there are more than 0 captures std::function can be used instead of plain function pointers.