在c++ 11中编译时检查用户定义的字符串字面值的大小



我试图限制使用一些用户定义的字符串给定长度

的字面量
Carte operator"" _C (const char* str, std::size_t sz) {
if (sz != 2)
throw runtime_error("Wrong size of string");
return from_string(str);
}

这可以完美地工作,除了因为字面量在编译时是已知的,所以大小测试也可以在编译时进行。但是我不能在这里使用静态断言

jeu.cpp:105:17: error: static_assert expression is not an integral constant expression
static_assert(sz == 2, "Wrong size of string");
^~~~~~~
jeu.cpp:105:17: note: read of non-const variable 'sz' is not allowed in a constant expression
jeu.cpp:104:51: note: declared here

是否有一种方法来检查用户定义的字符串字面量的大小在编译时在c++11 ?如果不能,是否可以使用最新的c++标准?

使用sizeof(test)获取长度。然后可以使用static_assert

const char test[] = "blablalba";
static_assert (sizeof(test) == 10);

最新更新