Static_assert with nonconstexpr objects in the hana tutorial
Reading the hana tutorial , I wonder how this might work static_assert
as expected:
template <typename Any>
auto switch_(Any& a) {
return [&a](auto ...cases_) {
auto cases = hana::make_tuple(cases_...);
auto default_ = hana::find_if(cases, [](auto const& c) {
return hana::first(c) == hana::type_c<default_t>;
});
static_assert(default_ != hana::nothing,
"switch is missing a default_ case");
// ...
};
}
The documentation explicitly states that default_
it is not an object constexpr
, so even if the overloading operator!=
for these types is a function constexpr
, the expression default_ != hana::nothing
cannot be a constant expression, since one of its arguments is not.
The tutorial says:
Notice how we can use static_assert as a result of comparing nothing, even if it
default_
is a non-constexpr object? Boldly, Hana makes sure that no information known at compile time is lost at runtime, which is obviously the case withdefault_
case.
What tutorial does this paragraph refer to, or how does this expression work?
source to share
You misunderstand what is required constexpr
. You can pass arguments << 20> in constexpr
, and the result can be constexpr
.
Example with a toy:
struct foo {
int x;
foo(int in):x(in){}
friend constexpr bool operator==(foo const&, foo const&) { return true; }
};
then
foo a{1}, b{2};
static_assert( a==b, "works" );
fine.
Hell, I can allocate those foo
on the heap and it ==
will evaluate as an expression constexpr
.
default_
not constexpr
, but comparing it with nothing
can be done using only the type information default_
available at compile time. Nothing compares to hana::nothing
, but (another instance) nothing.
struct toy_nothing_t {
friend constexpr bool operator==(toy_nothing_t const&, toy_nothing_t const&) {
return true;
}
template<class T>
friend constexpr bool operator==(T const&, toy_nothing_t const&) {
return false;
}
template<class T>
friend constexpr bool operator==(toy_nothing_t const&, T const&) {
return false;
}
};
this one toy_nothing_t
has similar properties.
source to share