简体   繁体   中英

What's the actual type in this lambda function?

I have a code that combines 3 lambda functions:

#include <functional>
#include <iostream>
using namespace std;

template <typename F, typename G, typename H>
    auto concat(F f, G g, H h) {
    return [=](auto... parameters) {
        return f( g( h( parameters... ) ) );
    };
}

int main() {
    auto func1 (
        [](int i) {
            return (i * 2);
        }
    );

    auto func2 (
        [](int i) {
            return (i % 2);
        }
    );

    auto combined (
        concat(func1, func2, greater<int>{})
    );

    cout << combined(3, 2) << endl;

    return 0;
}

My question is: what is the actual type (F, G, H) in template? Is it a function pointer, or a function object, or something else? How can I illustrate its type in code?

From cppreference :

The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type , known as closure type, which is declared (for the purposes of ADL) in the smallest block scope, class scope, or namespace scope that contains the lambda expression.

In other words, each lambda expression has a unique unnamed type. F and G are deduced as the type of the lambdas that you use to instantiate the template. It is not a function pointer.

For illustration you can consider that lambdas are syntactic sugar for functors. Ie the corresponding type for func1 is something similar to

struct "no name" {
    auto operator()(int i) const {
        return (i * 2);
    }
);

Every lambda expression has an unnamed unique class type, and the only way to refer to its type is to apply decltype to it.

In this particular instantiation of concat , the types are decltype(func1) , decltype(func2) , and greater<int> , respectively.
The result type is decltype(concat(func1, func2, greater<int>{})) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM