c++language-lawyerc++17empty-class

Construct an empty object without the default constructor


Suppose I have a type F. I know that F is empty, but F has no default constructor, so I can't use F() to construct it. Is there a way to obtain a valid object of type F anyway? I seem to recall a mention that there was such a way with arcane usage of unions. Ideally, it would be constexpr friendly.


This can be useful because captureless lambdas only gained a default constructor in C++20. In C++17, if I want to "pass a lambda to a template" and call that lambda without having an instance of it, I need to be able to reconstruct it from the type.

auto const f = [](int x) { return x; };
using F = decltype(f);

static_assert(std::is_empty_v<F>);
static_assert(!std::is_default_constructible_v<F>);

magically-construct-an-F(42);

Solution

  • For your own types, you could copy- or move-construct an object from itself: F f = f. This does not lead to UB by itself, see CWG363.