Why is this nested lambda not considered constexpr?

后端 未结 2 625
离开以前
离开以前 2021-01-12 14:44

I\'m trying to create a curried interface using nested constexpr lambdas, but the compiler does not consider it to be a constant expression.

namespace hana =         


        
2条回答
  •  不知归路
    2021-01-12 15:07

    I reduced your test case to this:

    #include 
    
    constexpr auto f = [](auto size) {
      return [=](){
        constexpr auto s = size();
        return 1;
      };
    };
    
    static_assert(f(std::integral_constant{})(), "");
    
    int main() { }
    

    As said in the comments above, this happens because size is not a constant expression from within the function body. This is not specific to Hana. As a workaround, you can use

    constexpr auto f = [](auto size) {
      return [=](){
        constexpr auto s = decltype(size)::value;
        return 1;
      };
    };
    

    or anything similar.

提交回复
热议问题