Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning lambda to std::function

Why is the 2nd assignment allowed, when the inferred return type is std::nullptr_t? With function pointers this is forbidden.

And why doesn't the 2nd lambda run?

#include <cstdio>
#include <functional>

int main()
{
    std::function<void* ()> f;

    f = []() -> void* {
        printf ("runs\n");
        return nullptr;
    };
    f();

    f = []() {
        printf ("doesn't run\n");
        return nullptr; // -> std::nullptr_t
    };
    f();

    return 0;
}
like image 545
Valentin Milea Avatar asked Nov 03 '12 19:11

Valentin Milea


1 Answers

std::function allows you to store anything, as long as the following holds for the signature you provided:

  • all argument types are implicitly convertible to the argument types of the stored callable entity, and
  • the return type of the stored callable entity is implicitly convertible to the return type of the signature

std::nullptr_t is implicitly convertible to any pointer type and yields the null pointer value of that pointer type.

Note that your code is not actually valid C++11, since you don't only have a return expr; in the second lambda, as such no return type deduction will happen. GCC (and Clang, IIRC) implement this as an extension, since it's going to be part of the standard at some time.

like image 84
Xeo Avatar answered Oct 17 '22 00:10

Xeo