[ad_1]
I have some constexpr
code that compiles and executes with MSVC, CLANG, and GCC. However, in Visual Studio 2022 latest, it places red squiggles under the function with the following (intellisense?) error listed:
“E0028 expression must have a constant value” This is followed by “attempt to access expired storage” followed by 6 lines that all are: “called from”
The problem is associated with the add()
method when using the vector::insert()
. It goes away if I use an alternate algorithm that doesn’t use insert
.
Here’s what the squiggles look like:
What is causing this? The code this subset is from compiles cleanly
Here’s the full code:
#include <algorithm>
#include <vector>
#include <initializer_list>
#include <array>
template<class T>
class A
{
public:
std::vector<T> v;
A() = default;
constexpr A(std::initializer_list<T> list)
{
for (auto& p1 : list)
v.push_back(p1);
}
constexpr A add(const A& new_rows) const
{
#if 0
// this works
A ret; ret.v.resize(v.size() + new_rows.v.size());
for (size_t i = 0; i < ret.v.size(); i++)
if (i < v.size())
ret.v[i] = v[i];
else
ret.v[i] = new_rows.v[i-v.size()];
#else
// Bug shows up in "else" intellisense errors: red underline of foo()
A ret = *this;
ret.v.insert(ret.v.end(), new_rows.v.begin(), new_rows.v.end());
#endif
return ret;
}
};
// return a std::array made from A
template <typename T, size_t a_rows>
constexpr auto make_std_array(const A<T>& mat)
{
std::array<T, a_rows> ret{};
for (size_t r = 0; r < a_rows; r++)
ret[r] = mat.v[r];
return ret;
}
constexpr auto foo()
{
A<int> z1{ 1,2,3,4 };
z1 = z1.add({5,6});
auto array = make_std_array<int,6>(z1);
return array;
}
constexpr auto z = foo();
int main()
{
constexpr auto x = foo();
return x[5]; // returns 6
}
[ad_2]