Std :: function <T> :: target when T is a free lambda

Consider the following code:

#include <functional>
#include <iostream>

void normalFunction()
{
    printf("bar");
}

int main()
{
    std::function<void ()> f1 = []()
    {
        printf("foo123");
    };

    std::function<void()> f2 = normalFunction;

    std::cout << f1.target<void (*)()>() << std::endl;
    std::cout << f2.target<void (*)()>() << std::endl;

    return 0;
}

The second line prints a valid address; the first call target, however, fails (returns nullptr), because the type of the stored caller is not void (), it is actually class <lambda_b356045a9ea53f6e7d502dd6abd8cae2>(as target_typetells us). This means that it std::function<T>::targetis very orthodox in type checking and requires an exact match - even if the lambda can be converted to void (*)()without any problems, as it is carefree.

? , C, . , , lambdas ; , , , std::function.

+4

Source: https://habr.com/ru/post/1651376/


All Articles