#include <variant>
struct S {
constexpr auto f() -> void {
// deleting the next line creates an error
if(std::holds_alternative<int>(m_var))
m_var.emplace<double>(5.0);
}
std::variant<int, double> m_var;
};
int main() {
return 0;
}
std::variant
has a non-constexpr
member function emplace()
. In general you can't use that in constexpr
functions. You can however if you surround that call by a condition that uses std::holds_alternative()
on that type. Also other constexpr functions as long as they're member functions in that class.
I'm having trouble to understand what' going on. My first reaction was to say that's a bug. That condition can't possibly be more constexpr than no condition at all. But maybe that was premature. Can anyone shed some light on this? Why is it that emplace()
is not constexpr but (equal-type) assignments are?
Edit: Maybe to expand a bit: One guess is that constructors and destructors of the involved variants could be non-constexpr and that's why emplace
etc are not. But the fun thing is that you can use conditions like this to compile the function as constexpr even when you explicitly abuse a non-constexpr constructor. That voids that argument.
godbolt: here.