Reputation: 594
I have a code like the snippet below:
#include <map>
//using namespace std;
int main(){
constexpr int defval = -2e9;
struct defint
{
int i = -defval;
bool operator==(const int& j) { return i == j; }
defint& operator=(int x) { i = x; return *this; }
};
std::map<char, defint> ci;
ci['a'] = 0;
}
This gives me C2065: 'defval': undeclared identifier
at the line int i = defval;
, but the defval
is obviously declared before. How do I use the declared const
in a struct
or class
so that the compiler sees it as it should? defval
is not declared anywhere before the definition in the snippet and the error appears only when I add the line that makes use of the map
, which is ci['a'] = 0;
. The compiler I am using is the one from MSVS 2022 with the C++20
standard.
Upvotes: -1
Views: 191
Reputation: 1
This seems to be a msvc bug and the program is well-formed.
There are two ways to solve this. Basically, msvc seems to have issue with defval
not having static storage duration. So the ways just give defval
static storage duration.
Solution 1
Here we add static constexpr
to defval
int main(){
//--------vvvvvv--------------------->added static
constexpr static int defval = -2e9;
//same code as before below
}
Solution 2
Another way of giving defval
a static storage duration is by making it global:
//no need to write static explicitly at global scope for constexpr variable
constexpr int defval = -2e9;
int main(){
//same code as before here
}
Here is the newly submitted msvc bug:
MSVC rejects use of constexpr local variable when used with std::map
Upvotes: 1