Test if a lambda is stateless?

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

    Boost.TypeTraits is_stateless seems to do the job for whatever reason without much drama:

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

    boost::is_stateless is simple the combination of other conditions, it can be expressed in terms of standard type traits I suppose:

    ::boost::is_stateless = 
    ::boost::has_trivial_constructor::value
    && ::boost::has_trivial_copy::value
    && ::boost::has_trivial_destructor::value
    && ::boost::is_class::value
    && ::boost::is_empty::value
    

    http://www.boost.org/doc/libs/1_60_0/libs/type_traits/doc/html/boost_typetraits/reference/is_stateless.html

    Check my other answer based on sizeof: https://stackoverflow.com/a/34873353/225186

提交回复
热议问题