如何返回带有私有比较器的 std::set
我想编写一个返回 std::set 自定义对象的 (C++) 方法。 然而,我不想公开插入对象时使用的比较器,因此我将其设为私有类。 我像这样创建集合:
std::set<some_class, some_class_comparator> return_object;
现在我想返回集合,所以它必须像这样进行转换(返回时隐式):
(const std::set<some_class>) return_object;
这就是编译器抱怨的地方。 有没有办法将带有比较器的可变集转换为不带比较器的不可变集?
非常感谢,
霍尔格
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不,因为
和
是不同的、完全不相关的类型。 模板就是模板——一种指定在编译之前如何生成类型的方法。 在第二种情况下,比较器是 std::set 附带的默认比较器。
是否有令人信服的理由表明 some_class_comparotor 需要是私有的? 它可以成为自己的独立实体吗? 难道只是你不想污染你的类的公共接口吗?
No because
and
are different, unrelated types entirely. Templates are just that, templates -- a way of specifying how a type is to be generated before compilation. In the second case, the comparator is the default comparer that a std::set would come with.
Is there a compelling reason that some_class_comparotor needs to be private? Could it be its own stand-alone entity? Is it just you don't want to pollute the public interface of your class?
我不这么认为。 AFAIK
std::set
只是std::set 的简写 >
因此该集合无法按照您想要的方式进行转换。我建议将项目转移到其他一些数据结构(例如向量)中,该结构将保持当前项目按顺序排列,而不需要比较器。
I don't think so. AFAIK
std::set<some_class>
is just shorthand forstd::set<some_class, std::less<some_class> >
so the set can't be converted as you want.I suggest transferring the items into some other data structure (e.g. a vector) that will maintain keep the current items in an order without needing a comparator.
你最好的解决方案是这样的:
Your best solution is something like this:
这是两种不同的类型 std::< 类型、比较器> 和 std::set< 类型,默认比较器>。
This is two different types std::< Type, Comparator > and std::set< Type, DefaultComparator >.
您想要向调用者隐藏实现细节,这听起来不像模板,而听起来像虚函数。 我认为首先你需要问自己,这真的很重要吗? 如果是这样,请将您的类隐藏在 IOpaqueSet 接口后面。 当然,其他 STL 操作就无法对其进行操作。
You want to hide an implementation detail from the caller, that doesn't sound like a template, that sounds like virtual functions. I think first, you need to ask yourself, does this really matter? If so, hide your class behind an IOpaqueSet interface. Of course, then no other STL operations could work on it.
STL 带有许多内置类,但它也是一个可扩展的框架。 如果你定义了你的::own::immutable_set,并定义了迭代器,其他STL算法就可以使用它。
immutable_set
将被定义为围绕可变std::set 的薄 const 包装器。 >
(需要一些模板魔法来支持不同的比较器,因为它们会导致不同的类型)。immutable_set::iterator::operator++
将转发到std::set::iterator::operator++
等。The STL comes with a lot of built-in classes, but it's also an extensible framework. If you define your::own::immutable_set, with iterators defined, other STL algorithms can use it.
immutable_set<T>
would be defined as a thin const wrapper around a mutablestd::set<T, comparator<T> >
(some template magic required to support different comparators, as they lead to different types).immutable_set<T>::iterator::operator++
would forward tostd::set<T>::iterator::operator++
, etc.