Can lambdas be used as non-type template parameter?

前端 未结 3 816
野性不改
野性不改 2021-01-03 00:02

Is the following code legal?

template 
struct A {};

int main () {
  auto lmb = [](int i){return i*i;};
  A a;
  return 0;
}
         


        
3条回答
  •  情歌与酒
    2021-01-03 00:58

    First, I think your lambda should be constexpr to be used as a non-type template parameter. I find it a bit weird, that it works.

    But then it should work in this case. The Standard tells us that a non-type template parameter can be a literal class type (that's a bit iffy since closures are literal but not really class types, I think they are explicitly included here) with the additional requirements that

    • All base clases and non-static members must be non-mutable and public
    • Their types must be structural or arrays thereof

    So we don't have problems in this easy example. But if you capture anything, your lambda has a non-public member variable and should be out. If that is not so sharp for closures, it definitely stops working if you capture something non-constexpr.

提交回复
热议问题