0

I'm trying to see if it's possible to use a parameter that is not default constructible within a lambda as part of a fold expression. Following code works if T is default constructible.

template <typename ...T>
struct X
{
   void foo()
   {
    ([](const T&)
    {
       if (sizeof(T) < 4)
       {
          std::cout << "Small block size: " << sizeof(T) << std::endl;
       }
    }(T{}), ...);

    // Print sizes
    ((std::cout << sizeof(T) << std::endl), ...);
   }
};

struct A {
   int a[100];
   };
struct B
{
};

int main()
{
   X<A,B> x;
   x.foo();
}

Output

Small block size: 1
400
1
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
user3882729
  • 1,339
  • 8
  • 11
  • 2
    Why do you think the fold or lambda has requirements for `T`? The part requiring default constructibility is clearly "`T{}`". – Potatoswatter Jan 10 '21 at 18:31
  • I'm not sure what you're looking for here. If `T` is not default-constructibe, you cannot default construct one. Therefore, you cannot call a function via template-argument-deduction based on such a type. The only way a lambda matters here is that pre-C++20, you can't use template arguments that aren't deduced. And even post-C++20, it'd still be awkward to call it. – Nicol Bolas Jan 10 '21 at 18:31
  • Have the lambda take `sizeof(T)` as the parameter. Or `T*` and pass `nullptr`. Since the value doesn't actually matter. – Igor Tandetnik Jan 10 '21 at 18:31

1 Answers1

4

The lambda doesn't need a parameter:

([]{
    if (sizeof(T) < 4)
    {
       std::cout << "Small block size: " << sizeof(T) << std::endl;
    }
}(), ...);
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207