Is that ill-formed or is just the compiler (g++-7 in my case) is just still buggy? because it says that n
is not defined.
template<class T>
auto tup(T const& t)
{
if constexpr(hana::length(t)() % 2)
auto n = hana::append(t, nullptr);
else
auto const& n = t;
return n;
}
int main()
{
std::cout << hana::length(tup(std::tuple(3, "h", 'c'))) << '\n';
}
n
will be always defined, no matter for which branch will the compiler go.
Your program is ill-formed because each n
is restricted to the scope of the single statement declaring it.
C++17 draft N4659 [stmt.select]/1 says:
The substatement in a selection-statement (each substatement, in the
else
form of theif
statement) implicitly defines a block scope ([basic.scope]). If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound statement containing the original substatement. [ Example:
if (x)
int i;
can be equivalently rewritten as
if (x) {
int i;
}
Thus after the
if
statement,i
is no longer in scope. - end example ]
This rule applies to all for
, while
, switch
, and if
statements - whether or not the constexpr
keyword is used with if
.
constexpr
change nothing in this case.
It's exactly like in this example
int foo (int a)
{
if ( a == 0 )
{
int r = 0;
}
else
{
int r = 0;
}
return r;
}
r
is defined in both cases. And with the same value.
But the scope of r
is limited to the if
and don't reach the return
.
If you can solve the problem returning immediatly; I mean
template<class T>
auto tup(T const& t)
{
if constexpr(hana::length(t)() % 2)
return hana::append(t, nullptr);
else
return t;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With