r/cpp • • Jan 26 '17

Stop calling "Function Objects" "Functors"

http://jackieokay.com/2017/01/26/functors.html
0 Upvotes

23 comments sorted by

View all comments

38

u/STL MSVC STL Dev Jan 26 '17

When I say function object, I’m referring to any type with a defined operator().

Actually, that isn't the Standard's formal definition, where a function object is anything that can be called with parentheses. This includes function pointers, classes with overloaded operator(), lambdas (special case of the previous one), and classes that are implicitly convertible to function pointers.

Granted, the latter basically never comes up except in <functional> unit tests.

Most C++ programmers can probably agree that C++11 lambda functions changed their lives.

On the other hand, "lambda function" drives me nuts. Lambdas aren't functions (or std::functions), but such terminology encourages confusion.

Formally, a functor is a mapping between categories that preserves identity morphisms and compositions of morphisms.

No, that's math. Programming is different. Mathematicians consider a "vector" to be different from what we consider it to be.

1

u/spotta Jan 26 '17

Lambdas aren't functions (or std::functions), but such terminology encourages confusion.

In the sense that lambdas are function objects? Or in some other sense?

classes that are implicitly convertible to function pointers.

?!? Huh? Is this just a class with a function pointer in the first memory location, or something more interesting than that?

9

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jan 26 '17

classes that are implicitly convertible to function pointers

constexpr int get_two() { return 2; }
using fptr = int(*)();

struct A
{
	constexpr operator fptr() { return &get_two; }
};

int main()
{
	static_assert(A{}() == 2);
}

1

u/spotta Jan 26 '17

Huh. This seems like a kind of weird way of doing operator(). Is there a functional difference between the two?

3

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jan 26 '17

This is not operator() - this is an user defined conversion

3

u/spotta Jan 26 '17

I know that it isn't operator(), I was curious what the difference between this and operator() is.

Though now that I think about it, that is pretty obvious... This is actually kind of a cute trick that I might have an application for. I'll have to look into this.