Reputation: 1223
I'm trying to put a static assert on the size of static const unordered_map member. But I get an error saying non-const condition for static assertion. Could someone help?
#include<unordered_map>
#include<string>
using namespace std;
class A{
public:
static const unordered_map<string,string> strMap;
};
const unordered_map<string,string> A::strMap ={{"key","value"}};
int main() {
static_assert(A::strMap.size() == 1, "sizes don't match");
}
EDIT: Based on the comments, I want to clarify, the following code works fine (it uses an array instead of a map):
#include<unordered_map>
#include<string>
using namespace std;
class A{
public:
static const pair<string,string> strMap[];
};
const pair<string,string> A::strMap[] ={{"key","value"}};
int main() {
//static_assert(sizeof(A::strMap)/sizeof(A::strMap[0]) == 2, "sizes don't match"); Fails to compile
static_assert(sizeof(A::strMap)/sizeof(A::strMap[0]) == 1, "sizes don't match"); //Compiles fine
}
Upvotes: 2
Views: 1528
Reputation: 62603
Can't do this. You'd need constexpr
std::unordered_map for this, and this is not possible, since it's constructor is not constexpr. And of course, no class which allocates memory (unordered_map
being of this kind) can declare it's constructor constexpr.
Upvotes: 4