在 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,大小测试也可以在那个时候完成。但是我不能在这里使用静态断言

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