我想要一个像 std::string
的类(例如 string_n
),这样 string_n
的对象不能超过N
个字符长。
N
可以在编译时指定。尝试创建更大长度的 string_n
可能会断言或引发异常。
一个选项类似于以下内容,但它会错过由std::string
提供的所有不错的成员函数。
template <size_t N>
class string_n {
char char_[N + 1];
};
另一种选择是推出如下所示的新类。
template <size_t N>
class string_n {
public:
// constructor and assignment operators with length check
~string_n() = default;
// for readers
const string& get() const;
private:
std::string string_;
};
这需要大量样板代码。
我感觉可能有更好的方法。你有什么建议?
最佳答案
这很接近:
template<size_t N, class CharT, class Traits = std::char_traits<CharT>>
struct basic_string_n:
std::array<CharT, N>,
std::experimental::basic_string_view<CharT, Traits>
{
using storage = std::array<CharT, N>;
using access = std::experimental::basic_string_view<CharT, Traits>;
using storage::operator[];
using storage::data;
using access::size;
basic_string_n(basic_string_n const& o):
storage(o),
access(regen(*this))
{}
basic_string_n& operator=(basic_string_n const& o)
{
*this = (storage const&)o;
*this = regen(*this);
return *this;
}
void remove_prefix(std::size_t n) = delete;
void remove_suffix(std::size_t n) = delete;
void swap( basic_string_n& other ) {
using std::swap;
swap( (storage&)*this, (storage&)other );
*this = regen(*this);
other = regen(other);
}
private:
friend access regen(storage& self) {
return {self.data(), CharT::length(self.data())};
}
};
这里我们将字符数组与 std::experimental::basic_string_view
混合在一起。缺少的是添加或删除字符的操作。
关于c++ - 如何限制 std::string 的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36018659/