Test if a lambda is stateless?

后端 未结 5 1430
春和景丽
春和景丽 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:18

    As per the Standard, if a lambda doesn't capture any variable, then it is implicitly convertible to function pointer.

    Based on that, I came up with is_stateless<> meta-function which tells you whether a lambda is stateless or not.

    #include 
    
    template 
    struct helper : helper
    {};
    
    template 
    struct helper 
    {
        static const bool value = std::is_convertible::value;
    };
    
    template
    struct is_stateless
    {
        static const bool value = helper::value;
    };
    

    And here is the test code:

    int main() 
    {
        int a;
        auto l1 = [a](){ return 1; };
        auto l2 = [](){ return 2; };
        auto l3 = [&a](){ return 2; };
    
        std::cout<::value<< "\n";
        std::cout<::value<< "\n";
        std::cout<::value<< "\n";
    }
    

    Output:

    false
    true
    false
    

    Online Demo.

提交回复
热议问题