samedi 20 février 2021

Checking the size of a user defined string litteral at compile time in C++11

I'm trying to restrict the use user defined litteral for string of a given length

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

This works perfectly except that since litteral is know at compile time, the size test could be done at that time as well. However the I can't use a static assert here

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

Is there a way to check the size of user defined string litteral at compile time in c++11 ? If not, is it possible with more recent standard of c++ ?

Aucun commentaire:

Enregistrer un commentaire