In C we do
char buffer[100];
Is there a way to declare a fixed size std::string
?
I don't know what you want to do, but with an std::array<char, 100> buffer;
you should do fine.
You can then get a string like this:
std::string str(std::begin(buffer),std::end(buffer);
You can use the string::reserve method like this
std::string s;
s.reserve(100);
But this isn't fixed size, because you can add more chars to the string with string::push_back for example.
In c++17, there will be std::string_view
which offers the same (immutable) interface as std::string
.
In the meantime, you can wrap a char array and add whatever services to it you choose, eg:
template<std::size_t N>
struct immutable_string
{
using ref = const char (&)[N+1];
constexpr immutable_string(ref s)
: s(s)
{}
constexpr auto begin() const { return (const char*)s; }
constexpr auto end() const { return begin() + size(); }
constexpr std::size_t size() const { return N; }
constexpr ref c_str() const { return s; }
ref s;
friend std::ostream& operator<<(std::ostream& os, immutable_string s)
{
return os.write(s.c_str(), s.size());
}
};
template<std::size_t NL, std::size_t NR>
std::string operator+(immutable_string<NL> l, immutable_string<NR> r)
{
std::string result;
result.reserve(l.size() + r.size());
result.assign(l.begin(), l.end());
result.insert(result.end(), r.begin(), r.end());
return result;
}
template<std::size_t N>
auto make_immutable_string(const char (&s) [N])
{
return immutable_string<N-1>(s);
}
int main()
{
auto x = make_immutable_string("hello, world");
std::cout << x << std::endl;
auto a = make_immutable_string("foo");
auto b = make_immutable_string("bar");
auto c = a + b;
std::cout << c << std::endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With