Search code examples
c++pointersfunction-pointersfunctorfunction-object

Proper way of returning a functor in C++


Consider we have an add function declared like this:

int add(const int a, const int b);

If we were to return this add function from foo...

std::function<int(const int, const int)> foo()
{
    return add;
}
std::function<int(const int, const int)> foo()
{
    return &add;
}

Which one of the above is the correct way of returning a function object since both work exactly the same?


Solution

  • Both code snippets are identical (as far as the language is concerned).

    std::function can be constructed from any callable object (whether it be a lambda, pointer-to-function, etc). In both examples, you are constructing the std::function with a function pointer.

    • In the first example, add denotes the name of a function -- which decays to a function pointer.

    • In the second example, the expression&add explicitly takes the address of a function, producing a function pointer.

    There is no "correct" convention as each are equally valid. What matters most in a code-base is consistency and readability; so I'd stick to whatever practice the existing code-base uses, or whichever practice is dictated in your organization's coding conventions.