[英]Can static_const<size_t>(), std::as_const() or static_cast<const size_t>() be used to declare an array?
I tried the three successive lines (each one of them alone) but no one of them worked.我尝试了三行连续的行(每行单独),但没有一行行得通。 Why??
为什么??
int main()
{
size_t j{8};
char arr[static_cast<const size_t>(j)]={'t'};
char arr[static_const<size_t>(j)]={'t'};
char arr[std::as_const(j)]={'t'};
arr[7]='\0';
std::cout<<arr;
return 0;
}
None of your 3 examples are constants at compile-time , because j
is not assigned a value until runtime .您的 3 个示例都不是编译时的常量,因为
j
直到运行时才被赋值。 No amount of casting j
will change that.任何铸造
j
都不会改变这一点。
To assign j
at compile-time, you need to declare it as const
(or constexpr
in C++11 and later) and then you can use j
as-is for declaring the array:要在编译时分配
j
,您需要将其声明为const
(或 C++11 及更高版本中的constexpr
),然后您可以按原样使用j
来声明数组:
int main()
{
const size_t j{8};
// or: constexpr size_t j{8};
char arr[j]={'t'};
arr[7]='\0';
std::cout<<arr;
return 0;
}
Ok, let's look at an updated bit of code - that actually compiles:好的,让我们看一下更新后的代码 - 实际上可以编译:
#include <iostream>
int main()
{
constexpr size_t j{8};
char arr[j]={'t'};
arr[7]='\0';
std::cout<<arr;
return 0;
}
j
is now a compile-time constant, suitable for using to size a built-in array. j
现在是一个编译时常量,适合用于调整内置数组的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.