Sudden problem with std::vector
Code:
uint32_t some_func() { return 32; }
int buf_1[32]; // <--- this always compiled with MSVC
int buf_2[some_func()]; // <--- whereas this fails because the buffer size needs to be known at compile time
In the past I always got around this by using std::vector - i.e.
Code:
uint32_t some_func() { return 32; }
const int x = some_func(); // <--- I'm sure these lines
std::vector<int> buf_3[x]; // <--- previously compiled
But all of a sudden this morning, the std::vector line is giving me C2131 because the value of x isn't known at compile time. I'm probably missing something obvious but I'm sure this used to compile okay... can anyone see what I'm doing wrong? :confused:
Re: Sudden problem with std::vector
Oops - I was using square brackets instead of round :blush:
This works...
Code:
std::vector<int> buf_3(x);
Re: Sudden problem with std::vector
Quote:
Originally Posted by
John E
Code:
int buf_2[some_func()]; // <--- whereas this fails because the buffer size needs to be known at compile time
It will work (in this case) if the function is declared constexpr.
Re: Sudden problem with std::vector
Thanks for the tip wolle. I'd never even heard of constexpr but you're right - it works fine!
Re: Sudden problem with std::vector
Quote:
Originally Posted by
John E
it works fine!
But, it only works if the function itself is executable at compile-time. If not, you still need to use an std::vector.
Re: Sudden problem with std::vector
Ah yes, you're right - in fact even something as simple as this doesn't work...
Code:
constexpr uint32_t some_func() { return sqrt(1024); }
Re: Sudden problem with std::vector
For a constexpr function to return a constexpr value, any functions it calls must also be marked as constexpr. ie. can be evaluated at compile time. Unfortunately, sqrt() isn't one of them.
See https://en.cppreference.com/w/cpp/language/constexpr
and the example of a compile-time factorial function.