+ 1

Cant we use static cast on double for std::array size?

Hi I am aware that std::array is compile time and it must need to know size of array in compilation stage. Also let me know if i am wrong but static cast to long int is also compile time operation. Isnt it ? (Only dynamic cast is run time operstion in four basic castings) If so, why still a5 is not inialized and results compile time error ? https://code.sololearn.com/c441XfmZlAtQ/?ref=app

21st Sep 2023, 6:20 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Respostas
+ 1
I had different opinion of static cast. It is compile time operation. But you named it as run time. Refer below: https://stackoverflow.com/questions/27309604/do-constant-and-reinterpret-cast-happen-at-compile-time Static cast is compile time only.
22nd Sep 2023, 4:04 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Hi, you are right about 'static_cast' is a compile-time operation, it's important to understand the context in which it's being used. in a5 declaration line, you're trying to use a non-constant value (dy, which is of type 'const double') as the size of the array. Even though the 'static_cast' is a compile-time operation, the value being casted (dy) is not know at compile time because it's based on a variable (const double dy) that can be determined only at runtime. Therefore, this usage is not allowed for determining the size of an std::array. If you want to specify the size of the array at compile time, you must use a constant expression, like you did with constexpr int z = 3; where 'z' is know at compile time.
22nd Sep 2023, 3:04 PM
Amine Laaboudi
Amine Laaboudi - avatar