繁体   English   中英

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

[英]Checking the size of a user defined string litteral at compile time in 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);
}

除了由于在编译时知道 litteral 之外,这非常有效,因此也可以在那时进行大小测试。 但是我不能在这里使用 static 断言

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM