Is there a limited-length string class around? I've searched a little on the net and didn't find anything. I'm interested in a class that limits (possibly at compile time) the length to 255, so marshalling the string's length only requires one byte.
+4
A:
You can make a wrapper arount std::string and force the length limit
Yassin
2010-04-15 19:11:15
Only at runtime.
anon
2010-04-15 19:12:14
Yes, but you can't do better if any of your string isn't a compile-time constant
Yassin
2010-04-15 19:13:43
A:
The issue of using a byte to address elements of the string probably means you'll need to write your own class with a [] operator and iterator that accepts / uses a uint8_t for indexing.
Depending on how you write it, some things you'll be able to enforce at compile time. For instance you could use a template argument to define the type you're going to use for indexing string elements.
andand
2010-04-15 19:16:04
He didn't indicate the index type (STL-style's size_type) should be 8-bit, just that's how he wants to serialize it.
Roger Pate
2010-04-15 19:33:01
I guess, then I don't fully understand why he wants to limit the length to 255 characters. If his question is really about marshalling the string, then why is it important that its length be limited?
andand
2010-04-15 20:24:26
@andand: He wants to limit the string to 255 characters because he needs to be able to store the length of the string as a byte.
bta
2010-04-15 21:08:10
@bta which is kind of my point; he asked about determining all of this a compile time and I suggested using templates as a compile time enforcement.
andand
2010-04-16 01:36:10
+1
A:
With C++0x you can use static_assert
#include <type_traits>
int main (void)
{
char test[] = "test";
static_assert(sizeof (test) <= 5, "Error: String too long!");
return 0;
}
Compile with:
g++ -std=c++0x test.cc
If you are not able to use C++0x. Then you can use the method described here:
namespace static_assert
{
template <bool> struct STATIC_ASSERT_FAILURE;
template <> struct STATIC_ASSERT_FAILURE<true> { enum { value = 1 }; };
template<int x> struct static_assert_test{};
}
#define COMPILE_ASSERT(x) \
typedef ::static_assert::static_assert_test<\
sizeof(::static_assert::STATIC_ASSERT_FAILURE< (bool)( x ) >)>\
_static_assert_typedef_
int main (void)
{
char test[] = "test";
COMPILE_ASSERT(sizeof (test) <= 5);
return 0;
}
matias
2010-04-15 21:04:09