我想扩展 std::string,但不是出于您可能认为的原因
我有一个有效地接受字符串的方法。但是,我想要使用的字符串子集非常有限。我正在考虑将 std::string 作为某个类进行 typedef'ing,并显式调用函数。不过,我不确定这是否有效。有想法吗?
I have a method that effectively takes a string. However, there is a very limited subset of strings I want to use. I was thinking of typedef'ing std::string as some class, and call the functions explicit. I'm not sure that would work, however. Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常的规则仍然适用:该类不是设计为继承的,并且它的析构函数不是虚拟的,因此如果您向上转换为 std::string 基类,并让该对象被销毁,您的派生类'析构函数不会被调用。
如果你能保证这种事永远不会发生,那就继续吧。
否则,您可以将 std::string 设为类的成员,而不是基类。或者你可以使用私有继承。这种方法的问题在于,您必须重新实现字符串接口才能使该类可用作字符串。
或者您可以定义您的类来公开一个 getString() 函数,该函数返回内部 std::string 对象。然后你仍然可以传递你自己的类,如果你尝试传递 std::string ,编译器会抱怨,但内部字符串在你需要时是可以访问的。这可能是最好的妥协。
The usual rule still applies: the class isn't designed to be inherited from, and its destructor isn't virtual, so if you ever upcast to the std::string base class, and let the object be destroyed, your derived class' destructor won't be called.
If you can guarantee that this will never happen, go ahead.
Otherwise, you could make the
std::string
a member of your class, rather than a base class. or you could use private inheritance. The problem with this approach is that you'd have to re-implement the string interface for the class to be usable as a string.Or you could just define your class to expose a
getString()
function which returns the internalstd::string
object. Then you can still pass your own class around, and the compiler will complain if you try to pass astd::string
, but the internal string is accessible when you need it. That might be the best compromise.听起来您想限制输入(即可能是只允许字母的字符串)。
我建议在类中使用字符串,然后包装您想要的函数。
It sounds like you want to limit the inputs (i.e. perhaps a string that only allows letters).
I would recommend using a string within a class and then wrapping the functions you want.
听起来您有一个接受受限字符串的方法。新班级真的有必要吗?
否则,您唯一想要捕获的是字符串是否满足限制。我认为 is_restricted_string() 和编译时类之间的唯一区别是性能,如果您有一个专用于检查字符串的存储结构。不要过早优化。也就是说,在新类中放入太多功能或像字符串一样使用它也是错误的。
It sounds like you have one method which accepts a restricted string. Is a new class really necessary?
Otherwise, the only thing you want to capture is whether a string satisfies the restrictions. The only difference I see between
is_restricted_string()
and a compile-time class is performance, in the case you have a storage structure dedicated to checked strings. Don't prematurely optimize. That said, it would also be an error to put too much functionality into your new class or to use it like a string.