Test if a lambda is stateless?

后端 未结 5 1436
春和景丽
春和景丽 2021-02-07 12:38

How would I go about testing if a lambda is stateless, that is, if it captures anything or not? My guess would be using overload resolution with a function pointer overload, or

5条回答
  •  春和景丽
    2021-02-07 13:23

    Per § 5.1.2/6

    The closure type for a non-generic lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function with C ++ language linkage (7.5) having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator. For a generic lambda with no lambda-capture, the closure type has a public non-virtual non-explicit const conversion function template to pointer to function.

    If it's convertible to a pointer to function, then MAYBE it has to not capture anything (stateless). In action:

    int v = 1;
    auto lambda1 = [ ]()->void {};
    auto lambda2 = [v]()->void {};
    
    using ftype = void(*)();
    
    ftype x = lambda1; // OK
    ftype y = lambda2; // Error
    

    You can also use std::is_convertible:

    static_assert(is_convertible::value, "no capture");
    static_assert(is_convertible::value, "by capture");
    

提交回复
热议问题