2

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?

Yiğit
  • 55
  • 6
  • 1
    Also consider `auto foo() -> int(&)(int, int) { return add; }`, where `&add` just doesn't work so there is a "correct" way – Artyer Jan 07 '21 at 07:53

1 Answers1

4

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.

Human-Compiler
  • 11,022
  • 1
  • 32
  • 59
  • I know that they are the same, but what is the generally accepted convention when doing this kind of thing? – Yiğit Jan 07 '21 at 05:39
  • 1
    There is no explicitly accepted convention (and in fact, such a question is off-topic for Stack-Overflow since it's opinion-based). Different organizations may have different preferences on convention, and any such convention may be equally valid. – Human-Compiler Jan 07 '21 at 05:41
  • I disagree that this question is off-topic. This particular question might not have an objective answer but for many other cases where one of the two (or many) functionally identical syntax is considered the "best-practice". I cannot know if its answer is "doesn't matter" or not, without asking. – Yiğit Jan 07 '21 at 05:50
  • I'd suggest adding "There is no explicitly accepted convention" sentence to the answer text. – Yiğit Jan 07 '21 at 05:53
  • 1
    I can add that to the answer, though the phrasing of the question does not make it clear that its asking about convention (which is why I have not added this yet). As for whether it's off-topic or not: just about anything that may be convention-based is generally off-topic, especially in C++ that does not have any standard coding conventions. What matters most is consistency. – Human-Compiler Jan 07 '21 at 05:55
  • 1
    Notice that conversion from function to function pointer inherit from C, for member pointer, there are no implicit conversion and `&` is required (`&MyClass::foo`), if it might guide about convention. – Jarod42 Jan 07 '21 at 10:06