Test if a lambda is stateless?

后端 未结 5 1502
春和景丽
春和景丽 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条回答
  •  萌比男神i
    2021-02-07 13:23

    An option could be to explicitly look a the size of the type, a stateless should in principle have the same size as other stateless types (I picked std::true_type for a reference type).

    #include
    #include
    
    template
    struct is_stateless_lambda : std::integral_constant{};
    
    int main(){
    
      auto l1 = [a](){ return 1; };
      auto l2 = [](){ return 2; };
      auto l3 = [&a](){ return 2; };
    
      assert( boost::is_stateless_lambda::value == false );
      assert( boost::is_stateless_lambda::value == true );
      assert( boost::is_stateless_lambda::value == false );
    }
    

    I don't know how portable this solution is. In any case check my other solution: https://stackoverflow.com/a/34873139/225186

提交回复
热议问题