tags:

views:

134

answers:

3

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
Only at runtime.
anon
Yes, but you can't do better if any of your string isn't a compile-time constant
Yassin
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
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
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
@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
@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
+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
But in most cases interesting strings are not known at compile-time.
UncleBens
@UncleBens: I agree, but the question was about trying to limit sizes possibly at compile time. Maybe in his case he has good reasons.
matias