-1

I'm trying to restrict the use of some user defined litteral for string to 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 known 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++ ?

oguz ismail
  • 1
  • 16
  • 47
  • 69
hivert
  • 10,579
  • 3
  • 31
  • 56
  • can try this trick ... https://stackoverflow.com/questions/25890784/computing-length-of-a-c-string-at-compile-time-is-this-really-a-constexpr – Kvae Kvae22 Feb 20 '21 at 10:43
  • @KvaeKvae22 Same problem : "read of non-constexpr variable 'str' is not allowed in a constant expression". The compiler doesn't seems to see that str and sz are constants. – hivert Feb 20 '21 at 10:59

1 Answers1

-1

use sizeof(test) to get length.. then you can use static_assert

const char test[] = "blablalba";
static_assert (sizeof(test) == 10);
Kvae Kvae22
  • 111
  • 1
  • 5
  • This doesn't work inside the function which makes the user defined litteral. The sizeof is on the parameter str (IE : pointer to char and not the string litteral). – hivert Feb 20 '21 at 14:39