在“if constexpr”块中声明的变量的范围
Scope of variables declared inside `if constexpr` blocks
这是
格式不正确还是只是编译器(在我的例子中为 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
不再在范围内。
此规则适用于所有for
、while
、switch
和if
语句 - 无论 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;
}
相关文章:
- 在疯狂的部分中声明变量
- 如何在C++中为高分辨率时钟声明变量?
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- CUDA 的性能取决于声明变量
- 如何在不为其声明变量的情况下获取和使用常量值的地址?
- C++声明变量时自动类型推断而不初始化
- 在不同循环中多次声明变量的优点
- 奇怪的错误 C2131 与 constexpr 声明变量
- 是否可以在 "if" 语句中声明变量?
- 在python-ctypes中声明变量并传递给dll函数
- 在递归函数C++中声明变量
- 只有一个定义/声明时标头声明变量的多堆定义错误
- 奇怪的未声明变量编译器错误
- 我在C++程序中声明变量时遇到问题
- 在命名空间中声明变量
- C++ lambda 按值捕获,而无需更早声明变量
- 声明变量以保存字符串列表时的内存分配
- 如何声明C 变量应突变
- 为什么允许在开关语句中声明变量?但不是声明 初始化
- 在同一命名空间中声明变量和函数是否出错?[C++]