简体   繁体   English

您应该如何为自定义类实现STL功能?

[英]How should you implement STL features for custom classes?

I'm implementing a tuple-like class, call it MyTuple , and I would like it to have some STL features, namely tuple_element , tuple_size , and get . 我正在实现一个类似于元组的类,称为MyTuple ,并且我希望它具有一些STL功能,即tuple_elementtuple_sizeget

  1. Should I implement tuple_element and tuple_size specializations in namespace std ? 我应该在namespace std实现tuple_elementtuple_size专业化吗? If not then how should I implement them? 如果没有,我应该如何实施它们?
  2. Since I'm not allowed to overload the STL get function, does that mean I must provide a separate get function in my own namespace, thereby forcing users to write using std::get; 由于不允许重载STL get函数,这是否意味着我必须在自己的名称空间中提供单独的get函数,从而迫使用户using std::get;进行编写using std::get; ?

Recall that there ain't no such thing as a partial specialization of function templates. 回想一下,不存在功能模板的部分专业化。 So you can't partially specialize std::tuple_element et al for your class. 因此,您不能为您的班级专门研究std::tuple_element等。

Normally, you would define free-standing functions that are logically part of your class' interface in the same namespace as the class itself. 通常,您应该在与类本身相同的名称空间中定义逻辑上属于类接口的独立函数。 Then you can rely on argument-dependent lookup to find them. 然后,您可以依靠依赖于参数的查找来找到它们。 std::get would be found by that same mechanism - users of your library will not in fact be forced to write using std::get . std :: get可以通过相同的机制找到-实际上,不会强迫您的库用户using std::get进行写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM