在“if constexpr”块中声明的变量的范围

Scope of variables declared inside `if constexpr` blocks

本文关键字:声明 变量 范围 if constexpr      更新时间:2023-10-16
这是

格式不正确还是只是编译器(在我的例子中为 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将始终定义,无论编译器将用于哪个分支。

程序格式不正确,因为每个n都限制在声明它的单个语句的作用域内。

C++17草案N4659 [stmt.select]/1说:

选择语句中的子语句

(每个子语句,采用if语句的else形式)隐式定义块作用域([basic.scope])。如果选择语句中的子语句是单个语句而不是复合语句,则就好像它被重写为包含原始子语句的复合语句一样。[ 示例:

if (x)
  int i;

可以等效地重写为

if (x) {
  int i;
}

因此,在if语句之后,i不再在范围内。

此规则适用于所有forwhileswitchif语句 - 无论 constexpr 关键字是否与 if 一起使用。

在这种情况下

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;
}