这是格式错误还是编译器(在我的例子中是g++-7)仍然是错误的?因为它说没有定义n。
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都将被定义。
发布于 2017-10-23 01:00:01
您的程序格式不正确,因为每个n被限制在声明它的单个语句的范围内。
C++17草案N4659 stmt.select/1说:
selection语句(每个子语句,以
else形式的if语句)中的子语句隐式定义块范围(basic.scope)。如果selection语句中的子语句是单个语句而不是复合语句,则就好像它被重写为包含原始子语句的复合语句。[例子:
if (x)
int i;可以等效地重写为
if (x) {
int i;
}因此,在
if语句之后,i不再在作用域中。-最终例子]
此规则适用于所有for、while、switch和if语句--无论constexpr关键字是否与if一起使用。
发布于 2017-10-23 01:07:44
在这种情况下,constexpr没有任何改变。
就像在这个例子中
int foo (int a)
{
if ( a == 0 )
{
int r = 0;
}
else
{
int r = 0;
}
return r;
}在这两种情况下都定义了r。而且有着同样的价值。
但是r的范围仅限于if,不能到达return。
如果你能立即解决问题,我的意思是
template<class T>
auto tup(T const& t)
{
if constexpr(hana::length(t)() % 2)
return hana::append(t, nullptr);
else
return t;
}https://stackoverflow.com/questions/46880578
复制相似问题